core/systems/PluginSys.cpp
author David Anderson <dvander@alliedmods.net>
Fri Jul 11 08:18:43 2008 +0000 (2008-07-11)
changeset 2193 db7c6362f3f2
parent 2113 8e8b28162e23
child 2210 79822782197b
permissions -rw-r--r--
landed massive refactoring of the JIT. contexts are actually contexts now, and a higher level structure wraps sp_plugin_t info. on that note, both sp_plugin_t and sp_context_t are entirely opaque, and not even core has access to them. amazingly, i managed to keep binary compatibility here although a large number of functions are deprecated (and core should eventually stop calling them).

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