core/systems/PluginSys.cpp
author Matt Woodrow <pred@alliedmods.net>
Thu Jul 31 21:08:00 2008 +0000 (2008-07-31)
changeset 2219 5ddd93671335
parent 2210 79822782197b
child 2226 d10b38524be3
permissions -rw-r--r--
Fixed a few file handle leaks
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <stdio.h>
    33 #include "PluginSys.h"
    34 #include "ShareSys.h"
    35 #include "LibrarySys.h"
    36 #include "HandleSys.h"
    37 #include "ForwardSys.h"
    38 #include "sourcemm_api.h"
    39 #include "sourcemod.h"
    40 #include "TextParsers.h"
    41 #include "Logger.h"
    42 #include "ExtensionSys.h"
    43 #include "sm_srvcmds.h"
    44 #include "sm_stringutil.h"
    45 #include "ConCmdManager.h"
    46 #include "PlayerManager.h"
    47 #include "CoreConfig.h"
    48 #include "Translator.h"
    49 
    50 CPluginManager g_PluginSys;
    51 HandleType_t g_PluginType = 0;
    52 IdentityType_t g_PluginIdent = 0;
    53 
    54 CPlugin::CPlugin(const char *file)
    55 {
    56 	static int MySerial = 0;
    57 
    58 	m_type = PluginType_Private;
    59 	m_status = Plugin_Uncompiled;
    60 	m_serial = ++MySerial;
    61 	m_pRuntime = NULL;
    62 	m_errormsg[256] = '\0';
    63 	snprintf(m_filename, sizeof(m_filename), "%s", file);
    64 	m_handle = 0;
    65 	m_ident = NULL;
    66 	m_pProps = sm_trie_create();
    67 	m_FakeNativesMissing = false;
    68 	m_LibraryMissing = false;
    69 	m_bGotAllLoaded = false;
    70 	m_pPhrases = g_Translator.CreatePhraseCollection();
    71 }
    72 
    73 CPlugin::~CPlugin()
    74 {
    75 	if (m_handle)
    76 	{
    77 		HandleSecurity sec;
    78 		sec.pOwner = g_PluginSys.GetIdentity();
    79 		sec.pIdentity = sec.pOwner;
    80 
    81 		g_HandleSys.FreeHandle(m_handle, &sec);
    82 		g_ShareSys.DestroyIdentity(m_ident);
    83 	}
    84 
    85 	if (m_pRuntime != NULL)
    86 	{
    87 		delete m_pRuntime;
    88 		m_pRuntime = NULL;
    89 	}
    90 
    91 	if (m_pProps)
    92 	{
    93 		sm_trie_destroy(m_pProps);
    94 	}
    95 	for (size_t i=0; i<m_configs.size(); i++)
    96 	{
    97 		delete m_configs[i];
    98 	}
    99 	m_configs.clear();
   100 	if (m_pPhrases != NULL)
   101 	{
   102 		m_pPhrases->Destroy();
   103 		m_pPhrases = NULL;
   104 	}
   105 }
   106 
   107 void CPlugin::InitIdentity()
   108 {
   109 	if (!m_handle)
   110 	{
   111 		m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
   112 		m_handle = g_HandleSys.CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
   113 		m_pRuntime->GetDefaultContext()->SetKey(1, m_ident);
   114 		m_pRuntime->GetDefaultContext()->SetKey(2, (IPlugin *)this);
   115 	}
   116 }
   117 
   118 unsigned int CPlugin::CalcMemUsage()
   119 {
   120 	unsigned int base_size = 
   121 		sizeof(CPlugin) 
   122 		+ sizeof(IdentityToken_t)
   123 		+ (m_configs.size() * (sizeof(AutoConfig *) + sizeof(AutoConfig)))
   124 		+ sm_trie_mem_usage(m_pProps);
   125 
   126 	for (unsigned int i = 0; i < m_configs.size(); i++)
   127 	{
   128 		base_size += m_configs[i]->autocfg.size();
   129 		base_size += m_configs[i]->folder.size();
   130 	}
   131 
   132 	for (List<String>::iterator i = m_Libraries.begin();
   133 		 i != m_Libraries.end();
   134 		 i++)
   135 	{
   136 		base_size += (*i).size();
   137 	}
   138 
   139 	for (List<String>::iterator i = m_RequiredLibs.begin();
   140 		 i != m_RequiredLibs.end();
   141 		 i++)
   142 	{
   143 		base_size += (*i).size();
   144 	}
   145 
   146 	return base_size;
   147 }
   148 
   149 Handle_t CPlugin::GetMyHandle()
   150 {
   151 	return m_handle;
   152 }
   153 
   154 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
   155 {
   156 	char fullpath[PLATFORM_MAX_PATH];
   157 	g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", file);
   158 	FILE *fp = fopen(fullpath, "rb");
   159 
   160 	CPlugin *pPlugin = new CPlugin(file);
   161 
   162 	if (!fp)
   163 	{
   164 		if (error)
   165 		{
   166 			snprintf(error, maxlength, "Unable to open file");
   167 		}
   168 		pPlugin->m_status = Plugin_BadLoad;
   169 		return pPlugin;
   170 	}
   171 
   172 	fclose(fp);
   173 
   174 	return pPlugin;
   175 }
   176 
   177 bool CPlugin::GetProperty(const char *prop, void **ptr, bool remove/* =false */)
   178 {
   179 	bool exists = sm_trie_retrieve(m_pProps, prop, ptr);
   180 
   181 	if (exists && remove)
   182 	{
   183 		sm_trie_delete(m_pProps, prop);
   184 	}
   185 
   186 	return exists;
   187 }
   188 
   189 bool CPlugin::SetProperty(const char *prop, void *ptr)
   190 {
   191 	return sm_trie_insert(m_pProps, prop, ptr);
   192 }
   193 
   194 IPluginRuntime *CPlugin::GetRuntime()
   195 {
   196 	return m_pRuntime;
   197 }
   198 
   199 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
   200 {
   201 	PluginStatus old_status = m_status;
   202 	m_status = status;
   203 
   204 	if (old_status == Plugin_Running)
   205 	{
   206 		/* Tell everyone we're now paused */
   207 		g_PluginSys._SetPauseState(this, true);
   208 	}
   209 
   210 	va_list ap;
   211 	va_start(ap, error_fmt);
   212 	vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
   213 	va_end(ap);
   214 
   215 	if (m_pRuntime != NULL)
   216 	{
   217 		m_pRuntime->SetPauseState(true);
   218 	}
   219 }
   220 
   221 void CPlugin::UpdateInfo()
   222 {
   223 	/* Now grab the info */
   224 	uint32_t idx;
   225 	IPluginContext *base = GetBaseContext();
   226 	int err = base->FindPubvarByName("myinfo", &idx);
   227 
   228 	memset(&m_info, 0, sizeof(m_info));
   229 
   230 	if (err == SP_ERROR_NONE)
   231 	{
   232 		struct sm_plugininfo_c_t
   233 		{
   234 			cell_t name;
   235 			cell_t description;
   236 			cell_t author;
   237 			cell_t version;
   238 			cell_t url;
   239 		};
   240 		sm_plugininfo_c_t *cinfo;
   241 		cell_t local_addr;
   242 
   243 		base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
   244 		base->LocalToString(cinfo->name, (char **)&m_info.name);
   245 		base->LocalToString(cinfo->description, (char **)&m_info.description);
   246 		base->LocalToString(cinfo->author, (char **)&m_info.author);
   247 		base->LocalToString(cinfo->url, (char **)&m_info.url);
   248 		base->LocalToString(cinfo->version, (char **)&m_info.version);
   249 	}
   250 
   251 	m_info.author = m_info.author ? m_info.author : "";
   252 	m_info.description = m_info.description ? m_info.description : "";
   253 	m_info.name = m_info.name ? m_info.name : "";
   254 	m_info.url = m_info.url ? m_info.url : "";
   255 	m_info.version = m_info.version ? m_info.version : "";
   256 
   257 	if ((err = base->FindPubvarByName("__version", &idx)) == SP_ERROR_NONE)
   258 	{
   259 		struct __version_info
   260 		{
   261 			cell_t version;
   262 			cell_t filevers;
   263 			cell_t date;
   264 			cell_t time;
   265 		};
   266 		__version_info *info;
   267 		cell_t local_addr;
   268 		const char *pDate, *pTime;
   269 
   270 		pDate = "";
   271 		pTime = "";
   272 
   273 		base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&info);
   274 		m_FileVersion = info->version;
   275 		if (m_FileVersion >= 3)
   276 		{
   277 			base->LocalToString(info->date, (char **)&pDate);
   278 			base->LocalToString(info->time, (char **)&pTime);
   279 			UTIL_Format(m_DateTime, sizeof(m_DateTime), "%s %s", pDate, pTime);
   280 		}
   281 	}
   282 	else
   283 	{
   284 		m_FileVersion = 0;
   285 	}
   286 }
   287 
   288 void CPlugin::Call_OnPluginStart()
   289 {
   290 	if (m_status != Plugin_Loaded)
   291 	{
   292 		return;
   293 	}
   294 
   295 	m_status = Plugin_Running;
   296 
   297 	cell_t result;
   298 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginStart");
   299 	if (!pFunction)
   300 	{
   301 		return;
   302 	}
   303 
   304 	int err;
   305 	if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
   306 	{
   307 		SetErrorState(Plugin_Error, "Error detected in plugin startup (see error logs)");
   308 	}
   309 }
   310 
   311 void CPlugin::Call_OnPluginEnd()
   312 {
   313 	if (m_status > Plugin_Paused)
   314 	{
   315 		return;
   316 	}
   317 
   318 	cell_t result;
   319 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginEnd");
   320 	if (!pFunction)
   321 	{
   322 		return;
   323 	}
   324 
   325 	pFunction->Execute(&result);
   326 }
   327 
   328 void CPlugin::Call_OnAllPluginsLoaded()
   329 {
   330 	if (m_status > Plugin_Paused)
   331 	{
   332 		return;
   333 	}
   334 
   335 	if (m_bGotAllLoaded)
   336 	{
   337 		return;
   338 	}
   339 
   340 	m_bGotAllLoaded = true;
   341 
   342 	cell_t result;
   343 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnAllPluginsLoaded");
   344 	if (pFunction != NULL)
   345 	{
   346 		pFunction->Execute(&result);
   347 	}
   348 
   349 	if (g_OnMapStarted)
   350 	{
   351 		if ((pFunction = m_pRuntime->GetFunctionByName("OnMapStart")) != NULL)
   352 		{
   353 			pFunction->Execute(NULL);
   354 		}
   355 	}
   356 
   357 	if (SM_AreConfigsExecuted())
   358 	{
   359 		SM_ExecuteForPlugin(GetBaseContext());
   360 	}
   361 }
   362 
   363 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
   364 {
   365 	if (m_status != Plugin_Created)
   366 	{
   367 		return false;
   368 	}
   369 
   370 	m_status = Plugin_Loaded;
   371 
   372 	int err;
   373 	cell_t result;
   374 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("AskPluginLoad");
   375 
   376 	if (!pFunction)
   377 	{
   378 		return true;
   379 	}
   380 
   381 	pFunction->PushCell(m_handle);
   382 	pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
   383 	pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
   384 	pFunction->PushCell(maxlength);
   385 	if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
   386 	{
   387 		return false;
   388 	}
   389 
   390 	if (!result || m_status != Plugin_Loaded)
   391 	{
   392 		return false;
   393 	}
   394 
   395 	return true;
   396 }
   397 
   398 void *CPlugin::GetPluginStructure()
   399 {
   400 	return NULL;
   401 }
   402 
   403 IPluginContext *CPlugin::GetBaseContext()
   404 {
   405 	if (m_pRuntime == NULL)
   406 	{
   407 		return NULL;
   408 	}
   409 
   410 	return m_pRuntime->GetDefaultContext();
   411 }
   412 
   413 sp_context_t *CPlugin::GetContext()
   414 {
   415 	return NULL;
   416 }
   417 
   418 const char *CPlugin::GetFilename()
   419 {
   420 	return m_filename;
   421 }
   422 
   423 PluginType CPlugin::GetType()
   424 {
   425 	return m_type;
   426 }
   427 
   428 const sm_plugininfo_t *CPlugin::GetPublicInfo()
   429 {
   430 	return &m_info;
   431 }
   432 
   433 unsigned int CPlugin::GetSerial()
   434 {
   435 	return m_serial;
   436 }
   437 
   438 PluginStatus CPlugin::GetStatus()
   439 {
   440 	return m_status;
   441 }
   442 
   443 bool CPlugin::IsDebugging()
   444 {
   445 	if (m_pRuntime == NULL)
   446 	{
   447 		return false;
   448 	}
   449 
   450 	return m_pRuntime->IsDebugging();
   451 }
   452 
   453 void CPlugin::LibraryActions(bool dropping)
   454 {
   455 	List<String>::iterator iter;
   456 	for (iter = m_Libraries.begin();
   457 		iter != m_Libraries.end();
   458 		iter++)
   459 	{
   460 		g_PluginSys.OnLibraryAction((*iter).c_str(), true, dropping);
   461 	}
   462 }
   463 
   464 bool CPlugin::SetPauseState(bool paused)
   465 {
   466 	if (paused && GetStatus() != Plugin_Running)
   467 	{
   468 		return false;
   469 	} else if (!paused && GetStatus() != Plugin_Paused) {
   470 		return false;
   471 	}
   472 
   473 	if (paused)
   474 	{
   475 		LibraryActions(true);
   476 	}
   477 
   478 	IPluginFunction *pFunction = m_pRuntime->GetFunctionByName("OnPluginPauseChange");
   479 	if (pFunction)
   480 	{
   481 		cell_t result;
   482 		pFunction->PushCell(paused ? 1 : 0);
   483 		pFunction->Execute(&result);
   484 	}
   485 
   486 	if (paused)
   487 	{
   488 		m_status = Plugin_Paused;
   489 		m_pRuntime->SetPauseState(true);
   490 	} else {
   491 		m_status = Plugin_Running;
   492 		m_pRuntime->SetPauseState(false);
   493 	}
   494 
   495 	g_PluginSys._SetPauseState(this, paused);
   496 
   497 	if (!paused)
   498 	{
   499 		LibraryActions(false);
   500 	}
   501 
   502 	return true;
   503 }
   504 
   505 IdentityToken_t *CPlugin::GetIdentity()
   506 {
   507 	return m_ident;
   508 }
   509 
   510 bool CPlugin::ToggleDebugMode(bool debug, char *error, size_t maxlength)
   511 {
   512 	int err;
   513 
   514 	if (!IsRunnable())
   515 	{
   516 		if (error)
   517 		{
   518 			snprintf(error, maxlength, "Plugin is not runnable.");
   519 		}
   520 		return false;
   521 	}
   522 
   523 	if (debug && IsDebugging())
   524 	{
   525 		if (error)
   526 		{
   527 			snprintf(error, maxlength, "Plugin is already in debug mode.");
   528 		}
   529 		return false;
   530 	}
   531 	else if (!debug && !IsDebugging())
   532 	{
   533 		if (error)
   534 		{
   535 			snprintf(error, maxlength, "Plugins is already in production mode.");
   536 		}
   537 		return false;
   538 	}
   539 
   540 	ICompilation *co = g_pSourcePawn2->StartCompilation();
   541 
   542 	if (!co->SetOption("debug", (debug) ? "1" : "0"))
   543 	{
   544 		if (error)
   545 		{
   546 			snprintf(error, maxlength, "Failed to change plugin mode (JIT failure).");
   547 		}
   548 		return false;
   549 	}
   550 
   551 	if ((err = m_pRuntime->ApplyCompilationOptions(co)) != SP_ERROR_NONE)
   552 	{
   553 		if (error)
   554 		{
   555 			snprintf(error, maxlength, "Failed to recompile plugin (JIT error %d).", err);
   556 		}
   557 		return false;
   558 	}
   559 
   560 	UpdateInfo();
   561 
   562 	return true;
   563 }
   564 
   565 bool CPlugin::IsRunnable()
   566 {
   567 	return (m_status <= Plugin_Paused) ? true : false;
   568 }
   569 
   570 time_t CPlugin::GetFileTimeStamp()
   571 {
   572 	char path[PLATFORM_MAX_PATH];
   573 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "plugins/%s", m_filename);
   574 #ifdef PLATFORM_WINDOWS
   575 	struct _stat s;
   576 	if (_stat(path, &s) != 0)
   577 #elif defined PLATFORM_POSIX
   578 	struct stat s;
   579 	if (stat(path, &s) != 0)
   580 #endif
   581 	{
   582 		return 0;
   583 	}
   584 	else
   585 	{
   586 		return s.st_mtime;
   587 	}
   588 }
   589 
   590 time_t CPlugin::GetTimeStamp()
   591 {
   592 	return m_LastAccess;
   593 }
   594 
   595 void CPlugin::SetTimeStamp(time_t t)
   596 {
   597 	m_LastAccess = t;
   598 }
   599 
   600 IPhraseCollection *CPlugin::GetPhrases()
   601 {
   602 	return m_pPhrases;
   603 }
   604 
   605 void CPlugin::DependencyDropped(CPlugin *pOwner)
   606 {
   607 	if (!m_pRuntime)
   608 	{
   609 		return;
   610 	}
   611 
   612 	List<String>::iterator reqlib_iter;
   613 	List<String>::iterator lib_iter;
   614 	for (lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++)
   615 	{
   616 		for (reqlib_iter=m_RequiredLibs.begin(); reqlib_iter!=m_RequiredLibs.end(); reqlib_iter++)
   617 		{
   618 			if ((*reqlib_iter) == (*lib_iter))
   619 			{
   620 				m_LibraryMissing = true;
   621 			}
   622 		}	
   623 	}
   624 
   625 	List<NativeEntry *>::iterator iter;
   626 	NativeEntry *pNative;
   627 	sp_native_t *native;
   628 	uint32_t idx;
   629 	unsigned int unbound = 0;
   630 
   631 	for (iter = pOwner->m_Natives.begin();
   632 		 iter != pOwner->m_Natives.end();
   633 		 iter++)
   634 	{
   635 		pNative = (*iter);
   636 		/* Find this native! */
   637 		if (m_pRuntime->FindNativeByName(pNative->name, &idx) != SP_ERROR_NONE)
   638 		{
   639 			continue;
   640 		}
   641 		/* Unbind it */
   642 		m_pRuntime->GetNativeByIndex(idx, &native);
   643 		native->pfn = NULL;
   644 		native->status = SP_NATIVE_UNBOUND;
   645 		unbound++;
   646 	}
   647 
   648 	if (unbound)
   649 	{
   650 		m_FakeNativesMissing = true;
   651 	}
   652 
   653 	/* :IDEA: in the future, add native trapping? */
   654 	if (m_FakeNativesMissing || m_LibraryMissing)
   655 	{
   656 		SetErrorState(Plugin_Error, "Depends on plugin: %s", pOwner->GetFilename());
   657 	}
   658 }
   659 
   660 unsigned int CPlugin::GetConfigCount()
   661 {
   662 	return (unsigned int)m_configs.size();
   663 }
   664 
   665 AutoConfig *CPlugin::GetConfig(unsigned int i)
   666 {
   667 	if (i >= GetConfigCount())
   668 	{
   669 		return NULL;
   670 	}
   671 
   672 	return m_configs[i];
   673 }
   674 
   675 void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
   676 {
   677 	/* Do a check for duplicates to prevent double-execution */
   678 	for (size_t i = 0; i < m_configs.size(); i++)
   679 	{
   680 		if (m_configs[i]->autocfg.compare(cfg) == 0
   681 			&& m_configs[i]->folder.compare(folder) == 0
   682 			&& m_configs[i]->create == autoCreate)
   683 		{
   684 			return;
   685 		}
   686 	}
   687 
   688 	AutoConfig *c = new AutoConfig;
   689 
   690 	c->autocfg = cfg;
   691 	c->folder = folder;
   692 	c->create = autoCreate;
   693 
   694 	m_configs.push_back(c);
   695 }
   696 
   697 void CPlugin::DropEverything()
   698 {
   699 	CPlugin *pOther;
   700 	List<CPlugin *>::iterator iter;
   701 	List<WeakNative>::iterator wk_iter;
   702 
   703 	/* Tell everyone that depends on us that we're about to drop */
   704 	for (iter = m_Dependents.begin();
   705 		 iter != m_Dependents.end(); 
   706 		 iter++)
   707 	{
   708 		pOther = (*iter);
   709 		pOther->DependencyDropped(this);
   710 	}
   711 
   712 	/* Note: we don't care about things we depend on. 
   713 	 * The reason is that extensions have their own cleanup 
   714 	 * code for plugins.  Although the "right" design would be 
   715 	 * to centralize that here, i'm omitting it for now.  Thus, 
   716 	 * the code below to walk the plugins list will suffice.
   717 	 */
   718 	
   719 	/* Other plugins could be holding weak references that were 
   720 	 * added by us.  We need to clean all of those up now.
   721 	 */
   722 	for (iter = g_PluginSys.m_plugins.begin();
   723 		 iter != g_PluginSys.m_plugins.end();
   724 		 iter++)
   725 	{
   726 		(*iter)->DropRefsTo(this);
   727 	}
   728 
   729 	/* Proceed with the rest of the necessities. */
   730 	CNativeOwner::DropEverything();
   731 }
   732 
   733 bool CPlugin::AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func)
   734 {
   735 	NativeEntry *pEntry;
   736 
   737 	if ((pEntry = g_ShareSys.AddFakeNative(pFunc, name, func)) == NULL)
   738 	{
   739 		return false;
   740 	}
   741 
   742 	m_Natives.push_back(pEntry);
   743 
   744 	return true;
   745 }
   746 
   747 /*******************
   748  * PLUGIN ITERATOR *
   749  *******************/
   750 
   751 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
   752 {
   753 	mylist = _mylist;
   754 	Reset();
   755 }
   756 
   757 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
   758 {
   759 	return (*current);
   760 }
   761 
   762 bool CPluginManager::CPluginIterator::MorePlugins()
   763 {
   764 	return (current != mylist->end());
   765 }
   766 
   767 void CPluginManager::CPluginIterator::NextPlugin()
   768 {
   769 	current++;
   770 }
   771 
   772 void CPluginManager::CPluginIterator::Release()
   773 {
   774 	g_PluginSys.ReleaseIterator(this);
   775 }
   776 
   777 CPluginManager::CPluginIterator::~CPluginIterator()
   778 {
   779 }
   780 
   781 void CPluginManager::CPluginIterator::Reset()
   782 {
   783 	current = mylist->begin();
   784 }
   785 
   786 /******************
   787  * PLUGIN MANAGER *
   788  ******************/
   789 
   790 CPluginManager::CPluginManager()
   791 {
   792 	m_LoadLookup = sm_trie_create();
   793 	m_AllPluginsLoaded = false;
   794 	m_MyIdent = NULL;
   795 	m_LoadingLocked = false;
   796 }
   797 
   798 CPluginManager::~CPluginManager()
   799 {
   800 	/* :NOTICE: 
   801 	 * Ignore the fact that there might be plugins in the cache.
   802 	 * This usually means that Core is not being unloaded properly, and everything
   803 	 * will crash anyway.  YAY
   804 	 */
   805 	sm_trie_destroy(m_LoadLookup);
   806 
   807 	CStack<CPluginManager::CPluginIterator *>::iterator iter;
   808 	for (iter=m_iters.begin(); iter!=m_iters.end(); iter++)
   809 	{
   810 		delete (*iter);
   811 	}
   812 	m_iters.popall();
   813 }
   814 
   815 void CPluginManager::Shutdown()
   816 {
   817 	List<CPlugin *>::iterator iter;
   818 
   819 	while ((iter = m_plugins.begin()) != m_plugins.end())
   820 	{
   821 		UnloadPlugin(*iter);
   822 	}
   823 }
   824 
   825 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
   826 {
   827 	/* First read in the database of plugin settings */
   828 	SMCError err;
   829 	SMCStates states;
   830 	m_AllPluginsLoaded = false;
   831 	if ((err=textparsers->ParseFile_SMC(config, &m_PluginInfo, &states)) != SMCError_Okay)
   832 	{
   833 		g_Logger.LogError("[SM] Encountered fatal error parsing file \"%s\"", config);
   834 		const char *err_msg = textparsers->GetSMCErrorString(err);
   835 		if (err_msg)
   836 		{
   837 			g_Logger.LogError("[SM] Parse error encountered: \"%s\"", err_msg);
   838 		}
   839 	}
   840 
   841 	LoadPluginsFromDir(basedir, NULL);
   842 }
   843 
   844 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
   845 {
   846 	char base_path[PLATFORM_MAX_PATH];
   847 
   848 	/* Form the current path to start reading from */
   849 	if (localpath == NULL)
   850 	{
   851 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
   852 	} else {
   853 		g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
   854 	}
   855 
   856 	IDirectory *dir = g_LibSys.OpenDirectory(base_path);
   857 
   858 	if (!dir)
   859 	{
   860 		char error[256];
   861 		g_LibSys.GetPlatformError(error, sizeof(error));
   862 		g_Logger.LogError("[SM] Failure reading from plugins path: %s", localpath);
   863 		g_Logger.LogError("[SM] Platform returned error: %s", error);
   864 		return;
   865 	}
   866 
   867 	while (dir->MoreFiles())
   868 	{
   869 		if (dir->IsEntryDirectory() 
   870 			&& (strcmp(dir->GetEntryName(), ".") != 0)
   871 			&& (strcmp(dir->GetEntryName(), "..") != 0)
   872 			&& (strcmp(dir->GetEntryName(), "disabled") != 0)
   873 			&& (strcmp(dir->GetEntryName(), "optional") != 0))
   874 		{
   875 			char new_local[PLATFORM_MAX_PATH];
   876 			if (localpath == NULL)
   877 			{
   878 				/* If no path yet, don't add a former slash */
   879 				snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
   880 			} else {
   881 				g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
   882 			}
   883 			LoadPluginsFromDir(basedir, new_local);
   884 		} else if (dir->IsEntryFile()) {
   885 			const char *name = dir->GetEntryName();
   886 			size_t len = strlen(name);
   887 			if (len >= 4
   888 				&& strcmp(&name[len-4], ".smx") == 0)
   889 			{
   890 				/* If the filename matches, load the plugin */
   891 				char plugin[PLATFORM_MAX_PATH];
   892 				if (localpath == NULL)
   893 				{
   894 					snprintf(plugin, sizeof(plugin), "%s", name);
   895 				} else {
   896 					g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
   897 				}
   898 				LoadAutoPlugin(plugin);
   899 			}
   900 		}
   901 		dir->NextEntry();
   902 	}
   903 	g_LibSys.CloseDirectory(dir);
   904 }
   905 
   906 LoadRes CPluginManager::_LoadPlugin(CPlugin **_plugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength)
   907 {
   908 	if (m_LoadingLocked)
   909 	{
   910 		return LoadRes_NeverLoad;
   911 	}
   912 
   913 	int err;
   914 	bool no_load = false;
   915 	PluginSettings *pset;
   916 	unsigned int setcount = m_PluginInfo.GetSettingsNum();
   917 	for (unsigned int i=0; i<setcount; i++)
   918 	{
   919 		if ((pset = m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
   920 		{
   921 			continue;
   922 		}
   923 		if (pset->blockload_val)
   924 		{
   925 			no_load = true;
   926 			break;
   927 		}
   928 	}
   929 
   930 	/**
   931 	 * Does this plugin already exist?
   932 	 */
   933 	CPlugin *pPlugin;
   934 	if (sm_trie_retrieve(m_LoadLookup, path, (void **)&pPlugin))
   935 	{
   936 		/* Check to see if we should try reloading it */
   937 		if (pPlugin->GetStatus() == Plugin_BadLoad
   938 			|| pPlugin->GetStatus() == Plugin_Error
   939 			|| pPlugin->GetStatus() == Plugin_Failed
   940 			|| no_load)
   941 		{
   942 			UnloadPlugin(pPlugin);
   943 		}
   944 		else
   945 		{
   946 			if (_plugin)
   947 			{
   948 				*_plugin = pPlugin;
   949 			}
   950 			return LoadRes_AlreadyLoaded;
   951 		}
   952 	}
   953 
   954 	if (no_load)
   955 	{
   956 		return LoadRes_NeverLoad;
   957 	}
   958 
   959 	pPlugin = CPlugin::CreatePlugin(path, error, maxlength);
   960 
   961 	assert(pPlugin != NULL);
   962 
   963 	pPlugin->m_type = PluginType_MapUpdated;
   964 
   965 	ICompilation *co = NULL;
   966 
   967 	if (pPlugin->m_status == Plugin_Uncompiled)
   968 	{
   969 		co = g_pSourcePawn2->StartCompilation();
   970 	}
   971 
   972 	for (unsigned int i=0; i<setcount; i++)
   973 	{
   974 		if ((pset=m_PluginInfo.GetSettingsIfMatch(i, path)) == NULL)
   975 		{
   976 			continue;
   977 		}
   978 		pPlugin->m_type = pset->type_val;
   979 		if (co)
   980 		{
   981 			for (unsigned int j=0; j<pset->opts_num; j++)
   982 			{
   983 				const char *key, *val;
   984 				m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
   985 				if (!key || !val)
   986 				{
   987 					continue;
   988 				}
   989 				if ((err = co->SetOption(key, val)) == SP_ERROR_NONE)
   990 				{
   991 					if (error)
   992 					{
   993 						snprintf(error, maxlength, "Unable to set JIT option (key \"%s\") (value \"%s\")", key, val);
   994 					}
   995 					co->Abort();
   996 					co = NULL;
   997 					break;
   998 				}
   999 			}
  1000 		}
  1001 	}
  1002 
  1003 	/* Do the actual compiling */
  1004 	if (co != NULL)
  1005 	{
  1006 		char fullpath[PLATFORM_MAX_PATH];
  1007 		g_SourceMod.BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", pPlugin->m_filename);
  1008 
  1009 		pPlugin->m_pRuntime = g_pSourcePawn2->LoadPlugin(co, fullpath, &err);
  1010 		if (pPlugin->m_pRuntime == NULL)
  1011 		{
  1012 			snprintf(error, 
  1013 				maxlength, 
  1014 				"Unable to load plugin (error %d: %s)", 
  1015 				err, 
  1016 				g_pSourcePawn2->GetErrorString(err));
  1017 		}
  1018 		else
  1019 		{
  1020 			pPlugin->UpdateInfo();
  1021 			pPlugin->m_status = Plugin_Created;
  1022 		}
  1023 	}
  1024 
  1025 	/* Get the status */
  1026 	if (pPlugin->GetStatus() == Plugin_Created)
  1027 	{
  1028 		/* First native pass - add anything from Core */
  1029 		g_ShareSys.BindNativesToPlugin(pPlugin, true);
  1030 		pPlugin->InitIdentity();
  1031 		if (pPlugin->Call_AskPluginLoad(error, maxlength))
  1032 		{
  1033 			/* Autoload any modules */
  1034 			LoadOrRequireExtensions(pPlugin, 1, error, maxlength);
  1035 		}
  1036 		else
  1037 		{
  1038 			pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1039 		}
  1040 	}
  1041 
  1042 	/* Save the time stamp */
  1043 	time_t t = pPlugin->GetFileTimeStamp();
  1044 	pPlugin->SetTimeStamp(t);
  1045 
  1046 	if (_plugin)
  1047 	{
  1048 		*_plugin = pPlugin;
  1049 	}
  1050 
  1051 	return (pPlugin->GetStatus() == Plugin_Loaded) ? LoadRes_Successful : LoadRes_Failure;
  1052 }
  1053 
  1054 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t maxlength, bool *wasloaded)
  1055 {
  1056 	CPlugin *pl;
  1057 	LoadRes res;
  1058 
  1059 	*wasloaded = false;
  1060 	if ((res=_LoadPlugin(&pl, path, debug, type, error, maxlength)) == LoadRes_Failure)
  1061 	{
  1062 		delete pl;
  1063 		return NULL;
  1064 	}
  1065 
  1066 	if (res == LoadRes_AlreadyLoaded)
  1067 	{
  1068 		*wasloaded = true;
  1069 		return pl;
  1070 	}
  1071 
  1072 	if (res == LoadRes_NeverLoad)
  1073 	{
  1074 		if (m_LoadingLocked)
  1075 		{
  1076 			UTIL_Format(error, maxlength, "There is a global plugin loading lock in effect");
  1077 		}
  1078 		else
  1079 		{
  1080 			UTIL_Format(error, maxlength, "This plugin is blocked from loading (see plugin_settings.cfg)");
  1081 		}
  1082 		return NULL;
  1083 	}
  1084 
  1085 	AddPlugin(pl);
  1086 
  1087 	/* Run second pass if we need to */
  1088 	if (IsLateLoadTime() && pl->GetStatus() == Plugin_Loaded)
  1089 	{
  1090 		if (!RunSecondPass(pl, error, maxlength))
  1091 		{
  1092 			UnloadPlugin(pl);
  1093 			return NULL;
  1094 		}
  1095 		pl->Call_OnAllPluginsLoaded();
  1096 	}
  1097 
  1098 	return pl;
  1099 }
  1100 
  1101 void CPluginManager::LoadAutoPlugin(const char *plugin)
  1102 {
  1103 	CPlugin *pl = NULL;
  1104 	LoadRes res;
  1105 	char error[255] = "Unknown error";
  1106 
  1107 	if ((res=_LoadPlugin(&pl, plugin, false, PluginType_MapUpdated, error, sizeof(error))) == LoadRes_Failure)
  1108 	{
  1109 		g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s", plugin, error);
  1110 		pl->SetErrorState(Plugin_Failed, "%s", error);
  1111 	}
  1112 
  1113 	if (res == LoadRes_Successful)
  1114 	{
  1115 		AddPlugin(pl);
  1116 	}
  1117 }
  1118 
  1119 void CPluginManager::AddPlugin(CPlugin *pPlugin)
  1120 {
  1121 	List<IPluginsListener *>::iterator iter;
  1122 	IPluginsListener *pListener;
  1123 
  1124 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1125 	{
  1126 		pListener = (*iter);
  1127 		pListener->OnPluginCreated(pPlugin);
  1128 	}
  1129 
  1130 	m_plugins.push_back(pPlugin);
  1131 	sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
  1132 }
  1133 
  1134 void CPluginManager::LoadAll_SecondPass()
  1135 {
  1136 	List<CPlugin *>::iterator iter;
  1137 	CPlugin *pPlugin;
  1138 
  1139 	char error[256];
  1140 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1141 	{
  1142 		pPlugin = (*iter);
  1143 		if (pPlugin->GetStatus() == Plugin_Loaded)
  1144 		{
  1145 			error[0] = '\0';
  1146 			if (!RunSecondPass(pPlugin, error, sizeof(error)))
  1147 			{
  1148 				g_Logger.LogError("[SM] Unable to load plugin \"%s\": %s", pPlugin->GetFilename(), error);
  1149 				pPlugin->SetErrorState(Plugin_Failed, "%s", error);
  1150 			}
  1151 		}
  1152 	}
  1153 
  1154 	m_AllPluginsLoaded = true;
  1155 }
  1156 
  1157 bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength)
  1158 {
  1159 	struct _pl
  1160 	{
  1161 		cell_t name;
  1162 		cell_t file;
  1163 		cell_t required;
  1164 	} *pl;
  1165 
  1166 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1167 	uint32_t num = pBase->GetPubVarsNum();
  1168 	sp_pubvar_t *pubvar;
  1169 	char *name, *file;
  1170 	char pathfile[PLATFORM_MAX_PATH];
  1171 
  1172 	for (uint32_t i=0; i<num; i++)
  1173 	{
  1174 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1175 		{
  1176 			continue;
  1177 		}
  1178 		if (strncmp(pubvar->name, "__pl_", 5) == 0)
  1179 		{
  1180 			pl = (_pl *)pubvar->offs;
  1181 			if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
  1182 			{
  1183 				continue;
  1184 			}
  1185 			if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
  1186 			{
  1187 				continue;
  1188 			}
  1189 			g_LibSys.GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
  1190 			if (strcmp(pathfile, file) == 0)
  1191 			{
  1192 				continue;
  1193 			}
  1194 			if (pl->required == false)
  1195 			{
  1196 				IPluginFunction *pFunc;
  1197 				char buffer[64];
  1198 				UTIL_Format(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
  1199 				if ((pFunc=pBase->GetFunctionByName(buffer)))
  1200 				{
  1201 					cell_t res;
  1202 					pFunc->Execute(&res);
  1203 					if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1204 					{
  1205 						if (error)
  1206 						{
  1207 							snprintf(error, maxlength, "Fatal error during initializing plugin load");
  1208 						}
  1209 						return false;
  1210 					}
  1211 				}
  1212 			}
  1213 			else
  1214 			{
  1215 				/* Check that we aren't registering the same library twice */
  1216 				if (pPlugin->m_RequiredLibs.find(name) == pPlugin->m_RequiredLibs.end())
  1217 				{
  1218 					pPlugin->m_RequiredLibs.push_back(name);
  1219 				}
  1220 				else
  1221 				{
  1222 					continue;
  1223 				}
  1224 				List<CPlugin *>::iterator iter;
  1225 				CPlugin *pl;
  1226 				bool found = false;
  1227 				for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  1228 				{
  1229 					pl = (*iter);
  1230 					if (pl->m_Libraries.find(name) != pl->m_Libraries.end())
  1231 					{
  1232 						found = true;
  1233 						break;
  1234 					}
  1235 				}
  1236 				if (!found)
  1237 				{
  1238 					if (error)
  1239 					{
  1240 						snprintf(error, maxlength, "Could not find required plugin \"%s\"", name);
  1241 					}
  1242 					return false;
  1243 				}
  1244 			}
  1245 		}
  1246 	}
  1247 
  1248 	return true;
  1249 }
  1250 
  1251 bool CPluginManager::LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength)
  1252 {
  1253 	/* Find any extensions this plugin needs */
  1254 	struct _ext
  1255 	{
  1256 		cell_t name;
  1257 		cell_t file;
  1258 		cell_t autoload;
  1259 		cell_t required;
  1260 	} *ext;
  1261 
  1262 	IPluginContext *pBase = pPlugin->GetBaseContext();
  1263 	uint32_t num = pBase->GetPubVarsNum();
  1264 	sp_pubvar_t *pubvar;
  1265 	IExtension *pExt;
  1266 	char path[PLATFORM_MAX_PATH];
  1267 	char *file, *name;
  1268 	for (uint32_t i=0; i<num; i++)
  1269 	{
  1270 		if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  1271 		{
  1272 			continue;
  1273 		}
  1274 		if (strncmp(pubvar->name, "__ext_", 6) == 0)
  1275 		{
  1276 			ext = (_ext *)pubvar->offs;
  1277 			if (pBase->LocalToString(ext->file, &file) != SP_ERROR_NONE)
  1278 			{
  1279 				continue;
  1280 			}
  1281 			if (pBase->LocalToString(ext->name, &name) != SP_ERROR_NONE)
  1282 			{
  1283 				continue;
  1284 			}
  1285 			if (pass == 1)
  1286 			{
  1287 				/* Attempt to auto-load if necessary */
  1288 				if (ext->autoload)
  1289 				{
  1290 					g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1291 					g_Extensions.LoadAutoExtension(path);
  1292 				}
  1293 			}
  1294 			else if (pass == 2)
  1295 			{
  1296 				/* Is this required? */
  1297 				if (ext->required)
  1298 				{
  1299 					g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
  1300 					if ((pExt = g_Extensions.FindExtensionByFile(path)) == NULL)
  1301 					{
  1302 						pExt = g_Extensions.FindExtensionByName(name);
  1303 					}
  1304 					/* :TODO: should we bind to unloaded extensions?
  1305 					 * Currently the extension manager will ignore this.
  1306 					 */
  1307 					if (!pExt || !pExt->IsRunning(NULL, 0))
  1308 					{
  1309 						if (error)
  1310 						{
  1311 							snprintf(error, maxlength, "Required extension \"%s\" file(\"%s\") not running", name, file);
  1312 						}
  1313 						return false;
  1314 					}
  1315 					else
  1316 					{
  1317 						g_Extensions.BindChildPlugin(pExt, pPlugin);
  1318 					}
  1319 				}
  1320 				else
  1321 				{
  1322 					IPluginFunction *pFunc;
  1323 					char buffer[64];
  1324 					UTIL_Format(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
  1325 
  1326 					if ((pFunc = pBase->GetFunctionByName(buffer)) != NULL)
  1327 					{
  1328 						cell_t res;
  1329 						pFunc->Execute(&res);
  1330 						if (pPlugin->GetBaseContext()->GetLastNativeError() != SP_ERROR_NONE)
  1331 						{
  1332 							if (error)
  1333 							{
  1334 								UTIL_Format(error, maxlength, "Fatal error during plugin initialization (ext req)");
  1335 							}
  1336 							return false;
  1337 						}
  1338 					}
  1339 				}
  1340 			}
  1341 		}
  1342 	}
  1343 
  1344 	return true;
  1345 }
  1346 
  1347 bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength)
  1348 {
  1349 	/* Second pass for extension requirements */
  1350 	if (!LoadOrRequireExtensions(pPlugin, 2, error, maxlength))
  1351 	{
  1352 		return false;
  1353 	}
  1354 
  1355 	if (!FindOrRequirePluginDeps(pPlugin, error, maxlength))
  1356 	{
  1357 		return false;
  1358 	}
  1359 
  1360 	/* Run another binding pass */
  1361 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1362 
  1363 	/* Find any unbound natives. Right now, these are not allowed. */
  1364 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1365 	uint32_t num = pContext->GetNativesNum();
  1366 	sp_native_t *native;
  1367 	for (unsigned int i=0; i<num; i++)
  1368 	{
  1369 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1370 		{
  1371 			break;
  1372 		}
  1373 		if (native->status == SP_NATIVE_UNBOUND
  1374 			&& native->name[0] != '@'
  1375 			&& !(native->flags & SP_NTVFLAG_OPTIONAL))
  1376 		{
  1377 			if (error)
  1378 			{
  1379 				snprintf(error, maxlength, "Native \"%s\" was not found", native->name);
  1380 			}
  1381 			return false;
  1382 		}
  1383 	}
  1384 
  1385 	/* Finish by telling all listeners */
  1386 	List<IPluginsListener *>::iterator iter;
  1387 	IPluginsListener *pListener;
  1388 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1389 	{
  1390 		pListener = (*iter);
  1391 		pListener->OnPluginLoaded(pPlugin);
  1392 	}
  1393 	
  1394 	/* Tell this plugin to finish initializing itself */
  1395 	pPlugin->Call_OnPluginStart();
  1396 
  1397 	/* Now, if we have fake natives, go through all plugins that might need rebinding */
  1398 	if (pPlugin->GetStatus() <= Plugin_Paused && pPlugin->m_Natives.size())
  1399 	{
  1400 		List<CPlugin *>::iterator pl_iter;
  1401 		CPlugin *pOther;
  1402 		for (pl_iter = m_plugins.begin();
  1403 			 pl_iter != m_plugins.end();
  1404 			 pl_iter++)
  1405 		{
  1406 			pOther = (*pl_iter);
  1407 			if ((pOther->GetStatus() == Plugin_Error
  1408 				&& (pOther->m_FakeNativesMissing || pOther->m_LibraryMissing))
  1409 				|| pOther->m_FakeNativesMissing)
  1410 			{
  1411 				TryRefreshDependencies(pOther);
  1412 			}
  1413 			else if ((pOther->GetStatus() == Plugin_Running
  1414 					  || pOther->GetStatus() == Plugin_Paused)
  1415 					 && pOther != pPlugin)
  1416 			{
  1417 				List<NativeEntry *>::iterator nv_iter;
  1418 				for (nv_iter = pPlugin->m_Natives.begin();
  1419 					 nv_iter != pPlugin->m_Natives.end();
  1420 					 nv_iter++)
  1421 				{
  1422 					g_ShareSys.BindNativeToPlugin(pOther, (*nv_iter));
  1423 				}
  1424 			}
  1425 		}
  1426 	}
  1427 
  1428 	/* Go through our libraries and tell other plugins they're added */
  1429 	List<String>::iterator s_iter;
  1430 	for (s_iter = pPlugin->m_Libraries.begin();
  1431 		s_iter != pPlugin->m_Libraries.end();
  1432 		s_iter++)
  1433 	{
  1434 		OnLibraryAction((*s_iter).c_str(), true, false);
  1435 	}
  1436 
  1437 	/* :TODO: optimize? does this even matter? */
  1438 	pPlugin->GetPhrases()->AddPhraseFile("core.phrases");
  1439 
  1440 	return true;
  1441 }
  1442 
  1443 void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
  1444 {
  1445 	assert(pPlugin->GetBaseContext() != NULL);
  1446 
  1447 	g_ShareSys.BindNativesToPlugin(pPlugin, false);
  1448 
  1449 	List<String>::iterator lib_iter;
  1450 	List<String>::iterator req_iter;
  1451 	List<CPlugin *>::iterator pl_iter;
  1452 	CPlugin *pl;
  1453 	for (req_iter=pPlugin->m_RequiredLibs.begin(); req_iter!=pPlugin->m_RequiredLibs.end(); req_iter++)
  1454 	{
  1455 		bool found = false;
  1456 		for (pl_iter=m_plugins.begin(); pl_iter!=m_plugins.end(); pl_iter++)
  1457 		{
  1458 			pl = (*pl_iter);
  1459 			for (lib_iter=pl->m_Libraries.begin(); lib_iter!=pl->m_Libraries.end(); lib_iter++)
  1460 			{
  1461 				if ((*req_iter) == (*lib_iter))
  1462 				{
  1463 					found = true;
  1464 				}
  1465 			}
  1466 		}
  1467 		if (!found)
  1468 		{
  1469 			pPlugin->SetErrorState(Plugin_Error, "Library not found: %s", (*req_iter).c_str());
  1470 			return;
  1471 		}
  1472 	}
  1473 
  1474 	/* Find any unbound natives
  1475 	 * Right now, these are not allowed
  1476 	 */
  1477 	IPluginContext *pContext = pPlugin->GetBaseContext();
  1478 	uint32_t num = pContext->GetNativesNum();
  1479 	sp_native_t *native;
  1480 	for (unsigned int i=0; i<num; i++)
  1481 	{
  1482 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
  1483 		{
  1484 			break;
  1485 		}
  1486 		if (native->status == SP_NATIVE_UNBOUND && !(native->flags & SP_NTVFLAG_OPTIONAL))
  1487 		{
  1488 			pPlugin->SetErrorState(Plugin_Error, "Native not found: %s", native->name);
  1489 			return;
  1490 		}
  1491 	}
  1492 
  1493 	if (pPlugin->GetStatus() == Plugin_Error)
  1494 	{
  1495 		/* If we got here, all natives are okay again! */
  1496 		pPlugin->m_status = Plugin_Running;
  1497 		if (pPlugin->m_pRuntime->IsPaused())
  1498 		{
  1499 			pPlugin->m_pRuntime->SetPauseState(false);
  1500 			_SetPauseState(pPlugin, false);
  1501 		}
  1502 	}
  1503 }
  1504 
  1505 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
  1506 {
  1507 	CPlugin *pPlugin = (CPlugin *)plugin;
  1508 
  1509 	/* This prevents removal during insertion or anything else weird */
  1510 	if (m_plugins.find(pPlugin) == m_plugins.end())
  1511 	{
  1512 		return false;
  1513 	}
  1514 
  1515 	IPluginContext *pContext = plugin->GetBaseContext();
  1516 	if (pContext->IsInExec())
  1517 	{
  1518 		char buffer[255];
  1519 		UTIL_Format(buffer, sizeof(buffer), "sm plugins unload %s\n", plugin->GetFilename());
  1520 		engine->ServerCommand(buffer);
  1521 		return false;
  1522 	}
  1523 
  1524 	/* Remove us from the lookup table and linked list */
  1525 	m_plugins.remove(pPlugin);
  1526 	sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
  1527 
  1528 	/* Go through our libraries and tell other plugins they're gone */
  1529 	List<String>::iterator s_iter;
  1530 	for (s_iter = pPlugin->m_Libraries.begin();
  1531 		 s_iter != pPlugin->m_Libraries.end();
  1532 		 s_iter++)
  1533 	{
  1534 		OnLibraryAction((*s_iter).c_str(), true, true);
  1535 	}
  1536 
  1537 	List<IPluginsListener *>::iterator iter;
  1538 	IPluginsListener *pListener;
  1539 
  1540 	if (pPlugin->GetStatus() <= Plugin_Error)
  1541 	{
  1542 		/* Notify listeners of unloading */
  1543 		for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1544 		{
  1545 			pListener = (*iter);
  1546 			pListener->OnPluginUnloaded(pPlugin);
  1547 		}
  1548 		/* Notify plugin */
  1549 		pPlugin->Call_OnPluginEnd();
  1550 	}
  1551 
  1552 	pPlugin->DropEverything();
  1553 
  1554 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  1555 	{
  1556 		/* Notify listeners of destruction */
  1557 		pListener = (*iter);
  1558 		pListener->OnPluginDestroyed(pPlugin);
  1559 	}
  1560 	
  1561 	/* Tell the plugin to delete itself */
  1562 	delete pPlugin;
  1563 
  1564 	return true;
  1565 }
  1566 
  1567 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
  1568 {
  1569 	IPlugin *pPlugin;
  1570 	IPluginContext *pContext;
  1571 
  1572 	pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
  1573 
  1574 	if (pContext->GetKey(2, (void **)&pPlugin))
  1575 	{
  1576 		return pPlugin;
  1577 	}
  1578 
  1579 	return NULL;
  1580 }
  1581 
  1582 CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
  1583 {
  1584 	return (CPlugin *)FindPluginByContext(ctx);
  1585 }
  1586 
  1587 unsigned int CPluginManager::GetPluginCount()
  1588 {
  1589 	return m_plugins.size();
  1590 }
  1591 
  1592 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
  1593 {
  1594 	m_listeners.push_back(listener);
  1595 }
  1596 
  1597 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
  1598 {
  1599 	m_listeners.remove(listener);
  1600 }
  1601 
  1602 IPluginIterator *CPluginManager::GetPluginIterator()
  1603 {
  1604 	if (m_iters.empty())
  1605 	{
  1606 		return new CPluginIterator(&m_plugins);
  1607 	} else {
  1608 		CPluginIterator *iter = m_iters.front();
  1609 		m_iters.pop();
  1610 		iter->Reset();
  1611 		return iter;
  1612 	}
  1613 }
  1614 
  1615 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
  1616 {
  1617 	m_iters.push(iter);
  1618 }
  1619 
  1620 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
  1621 {
  1622 	/* As an optimization, we do not call strlen, but compute the length in the first pass */
  1623 	size_t alias_len = 0;
  1624 	size_t local_len = 0;
  1625 
  1626 	const char *ptr = alias;
  1627 	unsigned int alias_explicit_paths = 0;
  1628 	unsigned int alias_path_end = 0;
  1629 	while (*ptr != '\0')
  1630 	{
  1631 		if (*ptr == '\\' || *ptr == '/')
  1632 		{
  1633 			alias_explicit_paths++;
  1634 			alias_path_end = alias_len;
  1635 		}
  1636 		alias_len++;
  1637 		ptr++;
  1638 	}
  1639 
  1640 	if (alias_explicit_paths && alias_path_end == alias_len - 1)
  1641 	{
  1642 		/* Trailing slash is totally invalid here */
  1643 		return false;
  1644 	}
  1645 
  1646 	ptr = localpath;
  1647 	unsigned int local_explicit_paths = 0;
  1648 	unsigned int local_path_end = 0;
  1649 	while (*ptr != '\0')
  1650 	{
  1651 		if (*ptr == '\\' || *ptr == '/')
  1652 		{
  1653 			local_explicit_paths++;
  1654 			local_path_end = local_len;
  1655 		}
  1656 		local_len++;
  1657 		ptr++;
  1658 	}
  1659 
  1660 	/* If the alias has more explicit paths than the real path,
  1661 	 * no match will be possible.
  1662 	 */
  1663 	if (alias_explicit_paths > local_explicit_paths)
  1664 	{
  1665 		return false;
  1666 	}
  1667 
  1668 	if (alias_explicit_paths)
  1669 	{
  1670 		/* We need to find if the paths match now.  For example, these should all match:
  1671 		 * csdm     csdm
  1672 		 * csdm     optional/csdm
  1673 		 * csdm/ban optional/crab/csdm/ban
  1674 		*/
  1675 		const char *aliasptr = alias;
  1676 		const char *localptr = localpath;
  1677 		bool match = true;
  1678 		do
  1679 		{
  1680 			if (*aliasptr != *localptr)
  1681 			{
  1682 				/* We have to knock one path off */
  1683 				local_explicit_paths--;
  1684 				if (alias_explicit_paths > local_explicit_paths)
  1685 				{
  1686 					/* Skip out if we're gonna have an impossible match */
  1687 					return false;
  1688 				}
  1689 				/* Eat up localptr tokens until we get a result */
  1690 				while (((localptr - localpath) < (int)local_path_end)
  1691 					&& *localptr != '/'
  1692 					&& *localptr != '\\')
  1693 				{
  1694 					localptr++;
  1695 				}
  1696 				/* Check if we hit the end of our searchable area.
  1697 				 * This probably isn't possible because of the path 
  1698 				 * count check, but it's a good idea anyway.
  1699 				 */
  1700 				if ((localptr - localpath) >= (int)local_path_end)
  1701 				{
  1702 					return false;
  1703 				} else {
  1704 					/* Consume the slash token */
  1705 					localptr++;
  1706 				}
  1707 				/* Reset the alias pointer so we can continue consuming */
  1708 				aliasptr = alias;
  1709 				match = false;
  1710 				continue;
  1711 			}
  1712 			/* Note:
  1713 			 * This is safe because if localptr terminates early, aliasptr will too
  1714 			 */
  1715 			do
  1716 			{
  1717 				/* We should never reach the end of the string because of this check. */
  1718 				bool aliasend = (aliasptr - alias) > (int)alias_path_end;
  1719 				bool localend = (localptr - localpath) > (int)local_path_end;
  1720 				if (aliasend || localend)
  1721 				{
  1722 					if (aliasend && localend)
  1723 					{
  1724 						/* we matched, and we can break out now */
  1725 						match = true;
  1726 						break;
  1727 					}
  1728 					/* Otherwise, we've hit the end somehow and rest won't match up.  Break out. */
  1729 					match = false;
  1730 					break;
  1731 				}
  1732 
  1733 				/* If we got here, it's safe to compare the next two tokens */
  1734 				if (*localptr != *aliasptr)
  1735 				{
  1736 					match = false;
  1737 					break;
  1738 				}
  1739 				localptr++;
  1740 				aliasptr++;
  1741 			} while (true);
  1742 		} while (!match);
  1743 	}
  1744 
  1745 	/* If we got here, it's time to compare filenames */
  1746 	const char *aliasptr = alias;
  1747 	const char *localptr = localpath;
  1748 
  1749 	if (alias_explicit_paths)
  1750 	{
  1751 		aliasptr = &alias[alias_path_end + 1];
  1752 	}
  1753 
  1754 	if (local_explicit_paths)
  1755 	{
  1756 		localptr = &localpath[local_path_end + 1];
  1757 	}
  1758 
  1759 	while (true)
  1760 	{
  1761 		if (*aliasptr == '*')
  1762 		{
  1763 			/* First, see if this is the last character */
  1764 			if ((unsigned)(aliasptr - alias) == alias_len - 1)
  1765 			{
  1766 				/* If so, there's no need to match anything else */
  1767 				return true;
  1768 			}
  1769 			/* Otherwise, we need to search for an appropriate matching sequence in local.
  1770 			 * Note that we only need to search up to the next asterisk.
  1771 			 */
  1772 			aliasptr++;
  1773 			bool match = true;
  1774 			const char *local_orig = localptr;
  1775 			do
  1776 			{
  1777 				match = true;
  1778 				while (*aliasptr != '\0' && *aliasptr != '*')
  1779 				{
  1780 					/* Since aliasptr is never '\0', localptr hitting the end will fail */
  1781 					if (*aliasptr != *localptr)
  1782 					{
  1783 						match = false;
  1784 						break;
  1785 					}
  1786 					aliasptr++;
  1787 					localptr++;
  1788 				}
  1789 				if (!match)
  1790 				{
  1791 					/* If we didn't get a match, we need to advance the search stream.
  1792 					 * This will let us skip tokens while still searching for another match.
  1793 					 */
  1794 					localptr = ++local_orig;
  1795 					/* Make sure we don't go out of bounds */
  1796 					if (*localptr == '\0')
  1797 					{
  1798 						break;
  1799 					}
  1800 				}
  1801 			} while (!match);
  1802 
  1803 			if (!match)
  1804 			{
  1805 				return false;
  1806 			} else {
  1807 				/* If we got a match, move on to the next token */
  1808 				continue;
  1809 			}
  1810 		} else if (*aliasptr == '\0') {
  1811 			if (*localptr == '\0'
  1812 				||
  1813 				strcmp(localptr, ".smx") == 0)
  1814 			{
  1815 				return true;
  1816 			} else {
  1817 				return false;
  1818 			}
  1819 		} else if (*aliasptr != *localptr) {
  1820 			return false;
  1821 		}
  1822 		aliasptr++;
  1823 		localptr++;
  1824 	}
  1825 
  1826 	return true;
  1827 }
  1828 
  1829 bool CPluginManager::IsLateLoadTime() const
  1830 {
  1831 	return (m_AllPluginsLoaded || !g_SourceMod.IsMapLoading());
  1832 }
  1833 
  1834 void CPluginManager::OnSourceModAllInitialized()
  1835 {
  1836 	m_MyIdent = g_ShareSys.CreateCoreIdentity();
  1837 
  1838 	HandleAccess sec;
  1839 	g_HandleSys.InitAccessDefaults(NULL, &sec);
  1840 
  1841 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY;
  1842 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
  1843 
  1844 	g_PluginType = g_HandleSys.CreateType("Plugin", this, 0, NULL, &sec, m_MyIdent, NULL);
  1845 	g_PluginIdent = g_ShareSys.CreateIdentType("PLUGIN");
  1846 
  1847 	g_RootMenu.AddRootConsoleCommand("plugins", "Manage Plugins", this);
  1848 
  1849 	g_ShareSys.AddInterface(NULL, this);
  1850 }
  1851 
  1852 void CPluginManager::OnSourceModShutdown()
  1853 {
  1854 	g_RootMenu.RemoveRootConsoleCommand("plugins", this);
  1855 
  1856 	UnloadAll();
  1857 
  1858 	g_HandleSys.RemoveType(g_PluginType, m_MyIdent);
  1859 	g_ShareSys.DestroyIdentType(g_PluginIdent);
  1860 	g_ShareSys.DestroyIdentity(m_MyIdent);
  1861 }
  1862 
  1863 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
  1864 {
  1865 	/* We don't care about the internal object, actually */
  1866 }
  1867 
  1868 bool CPluginManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
  1869 {
  1870 	*pSize = ((CPlugin *)object)->CalcMemUsage();
  1871 	return true;
  1872 }
  1873 
  1874 IPlugin *CPluginManager::PluginFromHandle(Handle_t handle, HandleError *err)
  1875 {
  1876 	IPlugin *pPlugin;
  1877 	HandleError _err;
  1878 
  1879 	HandleSecurity sec;
  1880 
  1881 	sec.pOwner = NULL;
  1882 	sec.pIdentity = m_MyIdent;
  1883 
  1884 	if ((_err=g_HandleSys.ReadHandle(handle, g_PluginType, &sec, (void **)&pPlugin)) != HandleError_None)
  1885 	{
  1886 		pPlugin = NULL;
  1887 	}
  1888 
  1889 	if (err)
  1890 	{
  1891 		*err = _err;
  1892 	}
  1893 
  1894 	return pPlugin;
  1895 }
  1896 
  1897 CPlugin *CPluginManager::GetPluginByOrder(int num)
  1898 {
  1899 	if (num < 1 || num > (int)GetPluginCount())
  1900 	{
  1901 		return NULL;
  1902 	}
  1903 
  1904 	CPlugin *pl;
  1905 	int id = 1;
  1906 
  1907 	SourceHook::List<CPlugin *>::iterator iter;
  1908 	for (iter = m_plugins.begin(); iter != m_plugins.end() && id < num; iter++, id++) {}
  1909 
  1910 	pl = *iter;
  1911 
  1912 	return pl;
  1913 }
  1914 
  1915 const char *CPluginManager::GetStatusText(PluginStatus st)
  1916 {
  1917 	switch (st)
  1918 	{
  1919 	case Plugin_Running:
  1920 		return "Running";
  1921 	case Plugin_Paused:
  1922 		return "Paused";
  1923 	case Plugin_Error:
  1924 		return "Error";
  1925 	case Plugin_Uncompiled:
  1926 		return "Uncompiled";
  1927 	case Plugin_BadLoad:
  1928 		return "Bad Load";
  1929 	case Plugin_Failed:
  1930 		return "Failed";
  1931 	default:
  1932 		assert(false);
  1933 		return "-";
  1934 	}
  1935 }
  1936 
  1937 void CPluginManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
  1938 {
  1939 	int argcount = command.ArgC();
  1940 	if (argcount >= 3)
  1941 	{
  1942 		const char *cmd = command.Arg(2);
  1943 		if (strcmp(cmd, "list") == 0)
  1944 		{
  1945 			char buffer[256];
  1946 			unsigned int id = 1;
  1947 			int plnum = GetPluginCount();
  1948 
  1949 			if (!plnum)
  1950 			{
  1951 				g_RootMenu.ConsolePrint("[SM] No plugins loaded");
  1952 				return;
  1953 			}
  1954 			else
  1955 			{
  1956 				g_RootMenu.ConsolePrint("[SM] Listing %d plugin%s:", GetPluginCount(), (plnum > 1) ? "s" : "");
  1957 			}
  1958 
  1959 			CPlugin *pl;
  1960 			SourceHook::List<CPlugin *>::iterator iter;
  1961 			SourceHook::List<CPlugin *> m_FailList;
  1962 
  1963 			for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  1964 			{
  1965 				pl = (*iter);
  1966 				assert(pl->GetStatus() != Plugin_Created);
  1967 				int len = 0;
  1968 				const sm_plugininfo_t *info = pl->GetPublicInfo();
  1969 				if (pl->GetStatus() != Plugin_Running)
  1970 				{
  1971 					len += UTIL_Format(buffer, sizeof(buffer), "  %02d <%s>", id, GetStatusText(pl->GetStatus()));
  1972 
  1973 					if (pl->GetStatus() <= Plugin_Error)
  1974 					{
  1975 						/* Plugin has failed to load. */
  1976 						m_FailList.push_back(pl);
  1977 					}
  1978 				}
  1979 				else
  1980 				{
  1981 					len += UTIL_Format(buffer, sizeof(buffer), "  %02d", id);
  1982 				}
  1983 				len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " \"%s\"", (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  1984 				if (IS_STR_FILLED(info->version))
  1985 				{
  1986 					len += UTIL_Format(&buffer[len], sizeof(buffer)-len, " (%s)", info->version);
  1987 				}
  1988 				if (IS_STR_FILLED(info->author))
  1989 				{
  1990 					UTIL_Format(&buffer[len], sizeof(buffer)-len, " by %s", info->author);
  1991 				}
  1992 				g_RootMenu.ConsolePrint("%s", buffer);
  1993 			}
  1994 
  1995 			if (!m_FailList.empty())
  1996 			{
  1997 				g_RootMenu.ConsolePrint("Load Errors:");
  1998 
  1999 				SourceHook::List<CPlugin *>::iterator _iter;
  2000 
  2001 				CPlugin *pl;
  2002 
  2003 				for (_iter=m_FailList.begin(); _iter!=m_FailList.end(); _iter++)
  2004 				{
  2005 					pl = (CPlugin *)*_iter;
  2006 					g_RootMenu.ConsolePrint("%s: %s",(IS_STR_FILLED(pl->GetPublicInfo()->name)) ? pl->GetPublicInfo()->name : pl->GetFilename(), pl->m_errormsg);
  2007 				}
  2008 			}
  2009 
  2010 			return;
  2011 		}
  2012 		else if (strcmp(cmd, "load") == 0)
  2013 		{
  2014 			if (argcount < 4)
  2015 			{
  2016 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins load <file>");
  2017 				return;
  2018 			}
  2019 
  2020 			char error[128];
  2021 			bool wasloaded;
  2022 			const char *filename = command.Arg(3);
  2023 
  2024 			char pluginfile[256];
  2025 			const char *ext = g_LibSys.GetFileExtension(filename) ? "" : ".smx";
  2026 			UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", filename, ext);
  2027 
  2028 			IPlugin *pl = LoadPlugin(pluginfile, false, PluginType_MapUpdated, error, sizeof(error), &wasloaded);
  2029 
  2030 			if (wasloaded)
  2031 			{
  2032 				g_RootMenu.ConsolePrint("[SM] Plugin %s is already loaded.", pluginfile);
  2033 				return;
  2034 			}
  2035 
  2036 			if (pl)
  2037 			{
  2038 				g_RootMenu.ConsolePrint("[SM] Loaded plugin %s successfully.", pluginfile);
  2039 			}
  2040 			else
  2041 			{
  2042 				g_RootMenu.ConsolePrint("[SM] Plugin %s failed to load: %s.", pluginfile, error);
  2043 			}
  2044 
  2045 			return;
  2046 		}
  2047 		else if (strcmp(cmd, "unload") == 0)
  2048 		{
  2049 			if (argcount < 4)
  2050 			{
  2051 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins unload <#|file>");
  2052 				return;
  2053 			}
  2054 
  2055 			CPlugin *pl;
  2056 			char *end;
  2057 			const char *arg = command.Arg(3);
  2058 			int id = strtol(arg, &end, 10);
  2059 
  2060 			if (*end == '\0')
  2061 			{
  2062 				pl = GetPluginByOrder(id);
  2063 				if (!pl)
  2064 				{
  2065 					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
  2066 					return;
  2067 				}
  2068 			}
  2069 			else
  2070 			{
  2071 				char pluginfile[256];
  2072 				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2073 				UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2074 
  2075 				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2076 				{
  2077 					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2078 					return;
  2079 				}
  2080 			}
  2081 
  2082 			char name[PLATFORM_MAX_PATH];
  2083 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2084 			strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2085 
  2086 			if (UnloadPlugin(pl))
  2087 			{
  2088 				g_RootMenu.ConsolePrint("[SM] Plugin %s unloaded successfully.", name);
  2089 			}
  2090 			else
  2091 			{
  2092 				g_RootMenu.ConsolePrint("[SM] Failed to unload plugin %s.", name);
  2093 			}
  2094 
  2095 			return;
  2096 		}
  2097 		else if (strcmp(cmd, "unload_all") == 0)
  2098 		{
  2099 			g_PluginSys.UnloadAll();
  2100 			g_RootMenu.ConsolePrint("[SM] All plugins have been unloaded.");
  2101 			return;
  2102 		}
  2103 		else if (strcmp(cmd, "load_lock") == 0)
  2104 		{
  2105 			if (m_LoadingLocked)
  2106 			{
  2107 				g_RootMenu.ConsolePrint("[SM] There is already a loading lock in effect.");
  2108 			}
  2109 			else
  2110 			{
  2111 				m_LoadingLocked = true;
  2112 				g_RootMenu.ConsolePrint("[SM] Loading is now locked; no plugins will be loaded or re-loaded.");
  2113 			}
  2114 			return;
  2115 		}
  2116 		else if (strcmp(cmd, "load_unlock") == 0)
  2117 		{
  2118 			if (m_LoadingLocked)
  2119 			{
  2120 				m_LoadingLocked = false;
  2121 				g_RootMenu.ConsolePrint("[SM] The loading lock is no longer in effect.");
  2122 			}
  2123 			else
  2124 			{
  2125 				g_RootMenu.ConsolePrint("[SM] There was no loading lock in effect.");
  2126 			}
  2127 			return;
  2128 		}
  2129 		else if (strcmp(cmd, "info") == 0)
  2130 		{
  2131 			if (argcount < 4)
  2132 			{
  2133 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins info <#>");
  2134 				return;
  2135 			}
  2136 
  2137 			CPlugin *pl;
  2138 			char *end;
  2139 			const char *arg = command.Arg(3);
  2140 			int id = strtol(arg, &end, 10);
  2141 
  2142 			if (*end == '\0')
  2143 			{
  2144 				pl = GetPluginByOrder(id);
  2145 				if (!pl)
  2146 				{
  2147 					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
  2148 					return;
  2149 				}
  2150 			}
  2151 			else
  2152 			{
  2153 				char pluginfile[256];
  2154 				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2155 				UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2156 
  2157 				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2158 				{
  2159 					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2160 					return;
  2161 				}
  2162 			}
  2163 
  2164 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2165 
  2166 			g_RootMenu.ConsolePrint("  Filename: %s", pl->GetFilename());
  2167 			if (pl->GetStatus() <= Plugin_Error)
  2168 			{
  2169 				if (IS_STR_FILLED(info->name))
  2170 				{
  2171 					if (IS_STR_FILLED(info->description))
  2172 					{
  2173 						g_RootMenu.ConsolePrint("  Title: %s (%s)", info->name, info->description);
  2174 					} else {
  2175 						g_RootMenu.ConsolePrint("  Title: %s", info->name);
  2176 					}
  2177 				}
  2178 				if (IS_STR_FILLED(info->author))
  2179 				{
  2180 					g_RootMenu.ConsolePrint("  Author: %s", info->author);
  2181 				}
  2182 				if (IS_STR_FILLED(info->version))
  2183 				{
  2184 					g_RootMenu.ConsolePrint("  Version: %s", info->version);
  2185 				}
  2186 				if (IS_STR_FILLED(info->url))
  2187 				{
  2188 					g_RootMenu.ConsolePrint("  URL: %s", info->url);
  2189 				}
  2190 				if (pl->GetStatus() == Plugin_Error)
  2191 				{
  2192 					g_RootMenu.ConsolePrint("  Error: %s", pl->m_errormsg);
  2193 				}
  2194 				else
  2195 				{
  2196 					if (pl->GetStatus() == Plugin_Running)
  2197 					{
  2198 						if (pl->IsDebugging())
  2199 						{
  2200 							g_RootMenu.ConsolePrint("  Status: running, debugging");
  2201 						}
  2202 						else
  2203 						{
  2204 							g_RootMenu.ConsolePrint("  Status: running");
  2205 						}
  2206 					}
  2207 					else
  2208 					{
  2209 						g_RootMenu.ConsolePrint("  Status: not running");
  2210 					}
  2211 
  2212 					const char *typestr = "";
  2213 					switch (pl->GetType())
  2214 					{
  2215 					case PluginType_MapUpdated:
  2216 						typestr = "Map Change if Updated";
  2217 						break;
  2218 					case PluginType_MapOnly:
  2219 						typestr = "Map Change";
  2220 						break;
  2221 					case PluginType_Private:
  2222 					case PluginType_Global:
  2223 						typestr = "Never";
  2224 						break;
  2225 					}
  2226 
  2227 					g_RootMenu.ConsolePrint("  Reloads: %s", typestr);
  2228 				}
  2229 				if (pl->m_FileVersion >= 3)
  2230 				{
  2231 					g_RootMenu.ConsolePrint("  Timestamp: %s", pl->m_DateTime);
  2232 				}
  2233 			}
  2234 			else
  2235 			{
  2236 				g_RootMenu.ConsolePrint("  Load error: %s", pl->m_errormsg);
  2237 				g_RootMenu.ConsolePrint("  File info: (title \"%s\") (version \"%s\")", 
  2238 										info->name ? info->name : "<none>",
  2239 										info->version ? info->version : "<none>");
  2240 				if (IS_STR_FILLED(info->url))
  2241 				{
  2242 					g_RootMenu.ConsolePrint("  File URL: %s", info->url);
  2243 				}
  2244 			}
  2245 
  2246 			return;
  2247 		}
  2248 		else if (strcmp(cmd, "debug") == 0)
  2249 		{
  2250 			if (argcount < 5)
  2251 			{
  2252 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins debug <#> [on|off]");
  2253 				return;
  2254 			}
  2255 
  2256 			CPlugin *pl;
  2257 			char *end;
  2258 			const char *arg = command.Arg(3);
  2259 			int id = strtol(arg, &end, 10);
  2260 
  2261 			if (*end == '\0')
  2262 			{
  2263 				pl = GetPluginByOrder(id);
  2264 				if (!pl)
  2265 				{
  2266 					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
  2267 					return;
  2268 				}
  2269 			}
  2270 			else
  2271 			{
  2272 				char pluginfile[256];
  2273 				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2274 				UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2275 
  2276 				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2277 				{
  2278 					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2279 					return;
  2280 				}
  2281 			}
  2282 
  2283 			int res;
  2284 			const char *mode = command.Arg(4);
  2285 			if ((res=strcmp("on", mode)) && strcmp("off", mode))
  2286 			{
  2287 				g_RootMenu.ConsolePrint("[SM] The only possible options are \"on\" and \"off.\"");
  2288 				return;
  2289 			}
  2290 
  2291 			bool debug;
  2292 			if (!res)
  2293 			{
  2294 				debug = true;
  2295 			}
  2296 			else
  2297 			{
  2298 				debug = false;
  2299 			}
  2300 
  2301 			if (debug && pl->IsDebugging())
  2302 			{
  2303 				g_RootMenu.ConsolePrint("[SM] This plugin is already in debug mode.");
  2304 				return;
  2305 			}
  2306 			else if (!debug && !pl->IsDebugging())
  2307 			{
  2308 				g_RootMenu.ConsolePrint("[SM] Debug mode is already disabled in this plugin.");
  2309 				return;
  2310 			}
  2311 
  2312 			char error[256];
  2313 			if (pl->ToggleDebugMode(debug, error, sizeof(error)))
  2314 			{
  2315 				g_RootMenu.ConsolePrint("[SM] Successfully toggled debug mode on plugin %s.", pl->GetFilename());
  2316 				return;
  2317 			}
  2318 			else
  2319 			{
  2320 				g_RootMenu.ConsolePrint("[SM] Could not toggle debug mode on plugin %s.", pl->GetFilename());
  2321 				g_RootMenu.ConsolePrint("[SM] Plugin returned error: %s", error);
  2322 				return;
  2323 			}
  2324 		}
  2325 		else if (strcmp(cmd, "refresh") == 0)
  2326 		{
  2327 			g_SourceMod.DoGlobalPluginLoads();
  2328 			g_RootMenu.ConsolePrint("[SM] The plugin list has been refreshed and reloaded.");
  2329 			return;
  2330 		}
  2331 		else if (strcmp(cmd, "reload") == 0)
  2332 		{
  2333 			if (argcount < 4)
  2334 			{
  2335 				g_RootMenu.ConsolePrint("[SM] Usage: sm plugins reload <#|file>");
  2336 				return;
  2337 			}
  2338 
  2339 			CPlugin *pl;
  2340 			char *end;
  2341 			const char *arg = command.Arg(3);
  2342 			int id = strtol(arg, &end, 10);
  2343 
  2344 			if (*end == '\0')
  2345 			{
  2346 				pl = GetPluginByOrder(id);
  2347 				if (!pl)
  2348 				{
  2349 					g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
  2350 					return;
  2351 				}
  2352 			}
  2353 			else
  2354 			{
  2355 				char pluginfile[256];
  2356 				const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2357 				UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2358 
  2359 				if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2360 				{
  2361 					g_RootMenu.ConsolePrint("[SM] Plugin %s is not loaded.", pluginfile);
  2362 					return;
  2363 				}
  2364 			}
  2365 
  2366 			char name[PLATFORM_MAX_PATH];
  2367 			const sm_plugininfo_t *info = pl->GetPublicInfo();
  2368 			strcpy(name, (IS_STR_FILLED(info->name)) ? info->name : pl->GetFilename());
  2369 
  2370 			if (ReloadPlugin(pl))
  2371 			{
  2372 				g_RootMenu.ConsolePrint("[SM] Plugin %s reloaded successfully.", name);
  2373 			}
  2374 			else
  2375 			{
  2376 				g_RootMenu.ConsolePrint("[SM] Failed to reload plugin %s.", name);
  2377 			}
  2378 
  2379 			return;
  2380 		}
  2381 	}
  2382 
  2383 	/* Draw the main menu */
  2384 	g_RootMenu.ConsolePrint("SourceMod Plugins Menu:");
  2385 	g_RootMenu.DrawGenericOption("debug", "Toggle debug mode on a plugin");
  2386 	g_RootMenu.DrawGenericOption("info", "Information about a plugin");
  2387 	g_RootMenu.DrawGenericOption("list", "Show loaded plugins");
  2388 	g_RootMenu.DrawGenericOption("load", "Load a plugin");
  2389 	g_RootMenu.DrawGenericOption("load_lock", "Prevents any more plugins from being loaded");
  2390 	g_RootMenu.DrawGenericOption("load_unlock", "Re-enables plugin loading");
  2391 	g_RootMenu.DrawGenericOption("refresh", "Reloads/refreshes all plugins in the plugins folder");
  2392 	g_RootMenu.DrawGenericOption("reload", "Reloads a plugin");
  2393 	g_RootMenu.DrawGenericOption("unload", "Unload a plugin");
  2394 	g_RootMenu.DrawGenericOption("unload_all", "Unloads all plugins");
  2395 }
  2396 
  2397 bool CPluginManager::ReloadPlugin(CPlugin *pl)
  2398 {
  2399 	List<CPlugin *>::iterator iter;
  2400 	char filename[PLATFORM_MAX_PATH];
  2401 	bool debug, wasloaded;
  2402 	PluginType ptype;
  2403 	IPlugin *newpl;
  2404 	int id = 1;
  2405 
  2406 	strcpy(filename, pl->m_filename);
  2407 	debug = pl->IsDebugging();
  2408 	ptype = pl->GetType();
  2409 
  2410 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++, id++)
  2411 	{
  2412 		if ((*iter) == pl)
  2413 		{
  2414 			break;
  2415 		}
  2416 	}
  2417 
  2418 	if (!UnloadPlugin(pl))
  2419 	{
  2420 		return false;
  2421 	}
  2422 	if (!(newpl=LoadPlugin(filename, debug, ptype, NULL, 0, &wasloaded)))
  2423 	{
  2424 		return false;
  2425 	}
  2426 
  2427 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2428 	{
  2429 		if ((*iter) == (CPlugin *)newpl)
  2430 		{
  2431 			m_plugins.erase(iter);
  2432 			break;
  2433 		}
  2434 	}
  2435 
  2436 	int i;
  2437 	for (i=1, iter=m_plugins.begin(); iter!=m_plugins.end() && i<id; iter++, i++)
  2438 	{
  2439 	}
  2440 	m_plugins.insert(iter, (CPlugin *)newpl);
  2441 
  2442 	return true;
  2443 }
  2444 
  2445 void CPluginManager::ReloadOrUnloadPlugins()
  2446 {
  2447 	/* If we're in a load lock, just skip this whole bit. */
  2448 	if (m_LoadingLocked)
  2449 	{
  2450 		return;
  2451 	}
  2452 
  2453 	List<CPlugin *>::iterator iter;
  2454 	List<CPlugin *> tmp_list = m_plugins;
  2455 	CPlugin *pl;
  2456 	time_t t;
  2457 
  2458 	for (iter=tmp_list.begin(); iter!=tmp_list.end(); iter++)
  2459 	{
  2460 		pl = (*iter);
  2461 		if (pl->GetType() ==  PluginType_MapOnly)
  2462 		{
  2463 			UnloadPlugin((IPlugin *)pl);
  2464 		}
  2465 		else if (pl->GetType() == PluginType_MapUpdated)
  2466 		{
  2467 			t = pl->GetFileTimeStamp();
  2468 			if (!t || t > pl->GetTimeStamp())
  2469 			{
  2470 				pl->SetTimeStamp(t);
  2471 				UnloadPlugin((IPlugin *)pl);
  2472 			}
  2473 		}
  2474 	}
  2475 }
  2476 
  2477 void CPluginManager::_SetPauseState(CPlugin *pl, bool paused)
  2478 {
  2479 	List<IPluginsListener *>::iterator iter;
  2480 	IPluginsListener *pListener;
  2481 	for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
  2482 	{
  2483 		pListener = (*iter);
  2484 		pListener->OnPluginPauseChange(pl, paused);
  2485 	}	
  2486 }
  2487 
  2488 void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward)
  2489 {
  2490 	List<CPlugin *>::iterator iter;
  2491 	CPlugin *pPlugin;
  2492 	IPluginFunction *pFunction;
  2493 
  2494 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++)
  2495 	{
  2496 		pPlugin = (*iter);
  2497 
  2498 		if (pPlugin->GetStatus() <= Plugin_Paused)
  2499 		{
  2500 			pFunction = pPlugin->GetBaseContext()->GetFunctionByName(name);
  2501 
  2502 			if (pFunction)
  2503 			{
  2504 				pForward->AddFunction(pFunction);
  2505 			}
  2506 		}
  2507 	}
  2508 }
  2509 
  2510 CPlugin *CPluginManager::GetPluginFromIdentity(IdentityToken_t *pToken)
  2511 {
  2512 	if (pToken->type != g_PluginIdent)
  2513 	{
  2514 		return NULL;
  2515 	}
  2516 
  2517 	return (CPlugin *)(pToken->ptr);
  2518 }
  2519 
  2520 void CPluginManager::OnLibraryAction(const char *lib, bool is_a_plugin, bool drop)
  2521 {
  2522 	List<CPlugin *>::iterator iter;
  2523 
  2524 	struct _pl
  2525 	{
  2526 		cell_t name;
  2527 		cell_t file;
  2528 		cell_t required;
  2529 	} *plc;
  2530 
  2531 	struct _ext
  2532 	{
  2533 		cell_t name;
  2534 		cell_t file;
  2535 		cell_t autoload;
  2536 		cell_t required;
  2537 	} *ext;
  2538 
  2539 	const char *name = drop ? "OnLibraryRemoved" : "OnLibraryAdded";
  2540 
  2541 	for (iter=m_plugins.begin();
  2542 		 iter!=m_plugins.end();
  2543 		 iter++)
  2544 	{
  2545 		CPlugin *pl = (*iter);
  2546 		if (pl->GetStatus() != Plugin_Running)
  2547 		{
  2548 			continue;
  2549 		}
  2550 		IPluginContext *pContext = pl->GetBaseContext();
  2551 		IPluginFunction *pf = pContext->GetFunctionByName(name);
  2552 		if (!pf)
  2553 		{
  2554 			continue;
  2555 		}
  2556 		uint32_t num_vars = pContext->GetPubVarsNum();
  2557 		for (uint32_t i=0; i<num_vars; i++)
  2558 		{
  2559 			sp_pubvar_t *pubvar;
  2560 			if (pContext->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
  2561 			{
  2562 				continue;
  2563 			}
  2564 			if (is_a_plugin && strncmp(pubvar->name, "__pl_", 5) == 0)
  2565 			{
  2566 				plc = (_pl *)pubvar->offs;
  2567 				if (plc->required)
  2568 				{
  2569 					continue;
  2570 				}
  2571 				char *str;
  2572 				pContext->LocalToString(plc->name, &str);
  2573 				if (strcmp(str, lib) != 0)
  2574 				{
  2575 					continue;
  2576 				}
  2577 				pf->PushString(lib);
  2578 				pf->Execute(NULL);
  2579 			}
  2580 			else if (!is_a_plugin && strncmp(pubvar->name, "__ext_", 6) == 0)
  2581 			{
  2582 				ext = (_ext *)pubvar->offs;
  2583 				if (ext->required)
  2584 				{
  2585 					continue;
  2586 				}
  2587 				char *str;
  2588 				pContext->LocalToString(ext->name, &str);
  2589 				if (strcmp(str, lib) != 0)
  2590 				{
  2591 					continue;
  2592 				}
  2593 				pf->PushString(lib);
  2594 				pf->Execute(NULL);
  2595 			}
  2596 		}
  2597 	}
  2598 }
  2599 
  2600 bool CPluginManager::LibraryExists(const char *lib)
  2601 {
  2602 	List<CPlugin *>::iterator iter;
  2603 
  2604 	for (iter=m_plugins.begin();
  2605 		 iter!=m_plugins.end();
  2606 		 iter++)
  2607 	{
  2608 		CPlugin *pl = (*iter);
  2609 		if (pl->GetStatus() != Plugin_Running)
  2610 		{
  2611 			continue;
  2612 		}
  2613 		List<String>::iterator s_iter;
  2614 		for (s_iter = pl->m_Libraries.begin();
  2615 			 s_iter != pl->m_Libraries.end();
  2616 			 s_iter++)
  2617 		{
  2618 			if ((*s_iter).compare(lib) == 0)
  2619 			{
  2620 				return true;
  2621 			}
  2622 		}
  2623 	}
  2624 
  2625 	return false;
  2626 }
  2627 
  2628 void CPluginManager::AllPluginsLoaded()
  2629 {
  2630 	List<CPlugin *>::iterator iter;
  2631 	CPlugin *pl;
  2632 
  2633 	for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
  2634 	{
  2635 		pl = (*iter);
  2636 		pl->Call_OnAllPluginsLoaded();
  2637 	}
  2638 }
  2639 
  2640 void CPluginManager::UnloadAll()
  2641 {
  2642 	List<CPlugin *>::iterator iter;
  2643 	while ( (iter = m_plugins.begin()) != m_plugins.end() )
  2644 	{
  2645 		UnloadPlugin((*iter));
  2646 	}
  2647 }
  2648 
  2649 int CPluginManager::GetOrderOfPlugin(IPlugin *pl)
  2650 {
  2651 	int id = 1;
  2652 	List<CPlugin *>::iterator iter;
  2653 
  2654 	for (iter = m_plugins.begin(); iter != m_plugins.end(); iter++, id++)
  2655 	{
  2656 		if ((*iter) == pl)
  2657 		{
  2658 			return id;
  2659 		}
  2660 	}
  2661 
  2662 	return -1;
  2663 }
  2664 
  2665 CPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg)
  2666 {
  2667 	int id;
  2668 	char *end;
  2669 	CPlugin *pl;
  2670 	
  2671 	id = strtol(arg, &end, 10);
  2672 
  2673 	if (*end == '\0')
  2674 	{
  2675 		pl = GetPluginByOrder(id);
  2676 		if (!pl)
  2677 		{
  2678 			return NULL;
  2679 		}
  2680 	}
  2681 	else
  2682 	{
  2683 		char pluginfile[256];
  2684 		const char *ext = g_LibSys.GetFileExtension(arg) ? "" : ".smx";
  2685 		UTIL_Format(pluginfile, sizeof(pluginfile), "%s%s", arg, ext);
  2686 
  2687 		if (!sm_trie_retrieve(m_LoadLookup, pluginfile, (void **)&pl))
  2688 		{
  2689 			return NULL;
  2690 		}
  2691 	}
  2692 
  2693 	return pl;
  2694 }