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