core/ExtensionSys.cpp
author David Anderson <dvander@alliedmods.net>
Sun Aug 30 00:03:58 2009 -0700 (2009-08-30)
changeset 2782 57d431498ac3
parent 2778 4a089866eb3e
child 2847 1daf209d9dd2
permissions -rw-r--r--
Removed auto folders (bug 3949).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2009 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 <stdlib.h>
    33 #include "ExtensionSys.h"
    34 #include "LibrarySys.h"
    35 #include "ShareSys.h"
    36 #include "Logger.h"
    37 #include "sourcemm_api.h"
    38 #include "sm_srvcmds.h"
    39 #include "sm_stringutil.h"
    40 
    41 CExtensionManager g_Extensions;
    42 IdentityType_t g_ExtType;
    43 
    44 void CExtension::Initialize(const char *filename, const char *path)
    45 {
    46 	m_pAPI = NULL;
    47 	m_pIdentToken = NULL;
    48 	unload_code = 0;
    49 	m_bFullyLoaded = false;
    50 	m_File.assign(filename);
    51 	m_Path.assign(path);
    52 	char real_name[PLATFORM_MAX_PATH];
    53 	g_LibSys.GetFileFromPath(real_name, sizeof(real_name), m_Path.c_str());
    54 	m_RealFile.assign(real_name);
    55 }
    56 
    57 CRemoteExtension::CRemoteExtension(IExtensionInterface *pAPI, const char *filename, const char *path)
    58 {
    59 	Initialize(filename, path);
    60 	m_pAPI = pAPI;
    61 }
    62 
    63 #if defined METAMOD_PLAPI_VERSION
    64 #if SOURCE_ENGINE == SE_LEFT4DEAD
    65 #define GAMEFIX "2.l4d"
    66 #elif SOURCE_ENGINE == SE_ORANGEBOX
    67 #define GAMEFIX "2.ep2"
    68 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
    69 #define GAMEFIX "2.ep2v"
    70 #elif SOURCE_ENGINE == SE_DARKMESSIAH
    71 #define GAMEFIX "2.darkm"
    72 #else
    73 #define GAMEFIX "2.ep1"
    74 #endif //SOURCE_ENGINE == SE_LEFT4DEAD
    75 #else  //METAMOD_PLAPI_VERSION
    76 #define GAMEFIX "1.ep1"
    77 #endif //METAMOD_PLAPI_VERSION
    78 
    79 CLocalExtension::CLocalExtension(const char *filename)
    80 {
    81 	m_PlId = 0;
    82 	m_pLib = NULL;
    83 
    84 	char path[PLATFORM_MAX_PATH];
    85 
    86 	/* Zeroth, see if there is an engine specific build in the new place. */
    87 	g_SourceMod.BuildPath(Path_SM,
    88 		path,
    89 		PLATFORM_MAX_PATH,
    90 		"extensions/%s." GAMEFIX "." PLATFORM_LIB_EXT,
    91 		filename);
    92 
    93 	if (g_LibSys.IsPathFile(path))
    94 	{
    95 		goto found;
    96 	}
    97 
    98 	/* First see if there is an engine specific build! */
    99 	g_SourceMod.BuildPath(Path_SM, 
   100 		path, 
   101 		PLATFORM_MAX_PATH,
   102 		"extensions/auto." GAMEFIX "/%s." PLATFORM_LIB_EXT,
   103 		filename);
   104 
   105 	/* Try the "normal" version */
   106 	if (!g_LibSys.IsPathFile(path))
   107 	{
   108 		g_SourceMod.BuildPath(Path_SM,
   109 			path,
   110 			PLATFORM_MAX_PATH,
   111 			"extensions/%s." PLATFORM_LIB_EXT,
   112 			filename);
   113 	}
   114 
   115 found:
   116 	Initialize(filename, path);
   117 }
   118 
   119 bool CRemoteExtension::Load(char *error, size_t maxlength)
   120 {
   121 	if (!PerformAPICheck(error, maxlength))
   122 	{
   123 		m_pAPI = NULL;
   124 		return false;
   125 	}
   126 
   127 	if (!CExtension::Load(error, maxlength))
   128 	{
   129 		m_pAPI = NULL;
   130 		return false;
   131 	}
   132 
   133 	return true;
   134 }
   135 
   136 bool CLocalExtension::Load(char *error, size_t maxlength)
   137 {
   138 	m_pLib = g_LibSys.OpenLibrary(m_Path.c_str(), error, maxlength);
   139 
   140 	if (m_pLib == NULL)
   141 	{
   142 		return false;
   143 	}
   144 
   145 	typedef IExtensionInterface *(*GETAPI)();
   146 	GETAPI pfnGetAPI = NULL;
   147 
   148 	if ((pfnGetAPI=(GETAPI)m_pLib->GetSymbolAddress("GetSMExtAPI")) == NULL)
   149 	{
   150 		m_pLib->CloseLibrary();
   151 		m_pLib = NULL;
   152 		snprintf(error, maxlength, "Unable to find extension entry point");
   153 		return false;
   154 	}
   155 
   156 	m_pAPI = pfnGetAPI();
   157 
   158 	/* Check pointer and version */
   159 	if (!PerformAPICheck(error, maxlength))
   160 	{
   161 		m_pLib->CloseLibrary();
   162 		m_pLib = NULL;
   163 		m_pAPI = NULL;
   164 		return false;
   165 	}
   166 
   167 	/* Load as MM:S */
   168 	if (m_pAPI->IsMetamodExtension())
   169 	{
   170 		bool already;
   171 		m_PlId = g_pMMPlugins->Load(m_Path.c_str(), g_PLID, already, error, maxlength);
   172 	}
   173 
   174 	if (!CExtension::Load(error, maxlength))
   175 	{
   176 		if (m_pAPI->IsMetamodExtension())
   177 		{
   178 			if (m_PlId)
   179 			{
   180 				char dummy[255];
   181 				g_pMMPlugins->Unload(m_PlId, true, dummy, sizeof(dummy));
   182 				m_PlId = 0;
   183 			}
   184 		}
   185 		m_pLib->CloseLibrary();
   186 		m_pLib = NULL;
   187 		m_pAPI = NULL;
   188 		return false;
   189 	}
   190 
   191 	return true;
   192 }
   193 
   194 void CRemoteExtension::Unload()
   195 {
   196 }
   197 
   198 void CLocalExtension::Unload()
   199 {
   200 	if (m_pAPI != NULL && m_PlId)
   201 	{
   202 		char temp_buffer[255];
   203 		g_pMMPlugins->Unload(m_PlId, true, temp_buffer, sizeof(temp_buffer));
   204 		m_PlId = 0;
   205 	}
   206 
   207 	if (m_pLib != NULL)
   208 	{
   209 		m_pLib->CloseLibrary();
   210 		m_pLib = NULL;
   211 	}
   212 }
   213 
   214 bool CRemoteExtension::Reload(char *error, size_t maxlength)
   215 {
   216 	snprintf(error, maxlength, "Remote extensions do not support reloading");
   217 	return false;
   218 }
   219 
   220 bool CLocalExtension::Reload(char *error, size_t maxlength)
   221 {
   222 	if (m_pLib == NULL) // FIXME: just load it instead?
   223 		return false;
   224 	
   225 	m_pAPI->OnExtensionUnload();
   226 	Unload();
   227 	
   228 	return Load(error, maxlength);
   229 }
   230 
   231 bool CRemoteExtension::IsExternal()
   232 {
   233 	return true;
   234 }
   235 
   236 bool CLocalExtension::IsExternal()
   237 {
   238 	return false;
   239 }
   240 
   241 CExtension::~CExtension()
   242 {
   243 	DestroyIdentity();
   244 }
   245 
   246 bool CExtension::PerformAPICheck(char *error, size_t maxlength)
   247 {
   248 	if (!m_pAPI)
   249 	{
   250 		snprintf(error, maxlength, "No IExtensionInterface instance provided");
   251 		return false;
   252 	}
   253 	
   254 	if (m_pAPI->GetExtensionVersion() > SMINTERFACE_EXTENSIONAPI_VERSION)
   255 	{
   256 		snprintf(error, maxlength, "Extension version is too new to load (%d, max is %d)", m_pAPI->GetExtensionVersion(), SMINTERFACE_EXTENSIONAPI_VERSION);
   257 		return false;
   258 	}
   259 
   260 	return true;
   261 }
   262 
   263 bool CExtension::Load(char *error, size_t maxlength)
   264 {
   265 	CreateIdentity();
   266 	if (!m_pAPI->OnExtensionLoad(this, &g_ShareSys, error, maxlength, !g_SourceMod.IsMapLoading()))
   267 	{
   268 		DestroyIdentity();
   269 		return false;
   270 	}
   271 	else
   272 	{
   273 		/* Check if we're past load time */
   274 		if (!g_SourceMod.IsMapLoading())
   275 		{
   276 			m_pAPI->OnExtensionsAllLoaded();
   277 		}
   278 	}
   279 
   280 	return true;
   281 }
   282 
   283 void CExtension::CreateIdentity()
   284 {
   285 	if (m_pIdentToken != NULL)
   286 	{
   287 		return;
   288 	}
   289 
   290 	m_pIdentToken = g_ShareSys.CreateIdentity(g_ExtType, this);
   291 }
   292 
   293 void CExtension::DestroyIdentity()
   294 {
   295 	if (m_pIdentToken == NULL)
   296 	{
   297 		return;
   298 	}
   299 
   300 	g_ShareSys.DestroyIdentity(m_pIdentToken);
   301 	m_pIdentToken = NULL;
   302 }
   303 
   304 void CExtension::MarkAllLoaded()
   305 {
   306 	assert(m_bFullyLoaded == false);
   307 	if (!m_bFullyLoaded)
   308 	{
   309 		m_bFullyLoaded = true;
   310 		m_pAPI->OnExtensionsAllLoaded();
   311 	}
   312 }
   313 
   314 void CExtension::AddPlugin(CPlugin *pPlugin)
   315 {
   316 	/* Unfortunately we have to do this :( */
   317 	if (m_Dependents.find(pPlugin) != m_Dependents.end())
   318 	{
   319 		m_Dependents.push_back(pPlugin);
   320 	}
   321 }
   322 
   323 void CExtension::SetError(const char *error)
   324 {
   325 	m_Error.assign(error);
   326 }
   327 
   328 IExtensionInterface *CExtension::GetAPI()
   329 {
   330 	return m_pAPI;
   331 }
   332 
   333 const char *CExtension::GetFilename()
   334 {
   335 	return m_RealFile.c_str();
   336 }
   337 
   338 IdentityToken_t *CExtension::GetIdentity()
   339 {
   340 	return m_pIdentToken;
   341 }
   342 
   343 bool CRemoteExtension::IsLoaded()
   344 {
   345 	return (m_pAPI != NULL);
   346 }
   347 
   348 bool CLocalExtension::IsLoaded()
   349 {
   350 	return (m_pLib != NULL);
   351 }
   352 
   353 void CExtension::AddDependency(const IfaceInfo *pInfo)
   354 {
   355 	if (m_Deps.find(*pInfo) == m_Deps.end())
   356 	{
   357 		m_Deps.push_back(*pInfo);
   358 	}
   359 }
   360 
   361 bool operator ==(const IfaceInfo &i1, const IfaceInfo &i2)
   362 {
   363 	return (i1.iface == i2.iface) && (i1.owner == i2.owner);
   364 }
   365 
   366 void CExtension::AddChildDependent(CExtension *pOther, SMInterface *iface)
   367 {
   368 	IfaceInfo info;
   369 	info.iface = iface;
   370 	info.owner = pOther;
   371 
   372 	List<IfaceInfo>::iterator iter;
   373 	for (iter = m_ChildDeps.begin();
   374 		 iter != m_ChildDeps.end();
   375 		 iter++)
   376 	{
   377 		IfaceInfo &other = (*iter);
   378 		if (other == info)
   379 		{
   380 			return;
   381 		}
   382 	}
   383 
   384 	m_ChildDeps.push_back(info);
   385 }
   386 
   387 ITERATOR *CExtension::FindFirstDependency(IExtension **pOwner, SMInterface **pInterface)
   388 {
   389 	List<IfaceInfo>::iterator iter = m_Deps.begin();
   390 
   391 	if (iter == m_Deps.end())
   392 	{
   393 		return NULL;
   394 	}
   395 
   396 	if (pOwner)
   397 	{
   398 		*pOwner = (*iter).owner;
   399 	}
   400 	if (pInterface)
   401 	{
   402 		*pInterface = (*iter).iface;
   403 	}
   404 
   405 	List<IfaceInfo>::iterator *pIter = new List<IfaceInfo>::iterator(iter);
   406 
   407 	return (ITERATOR *)pIter;
   408 }
   409 
   410 bool CExtension::FindNextDependency(ITERATOR *iter, IExtension **pOwner, SMInterface **pInterface)
   411 {
   412 	List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
   413 	List<IfaceInfo>::iterator _iter;
   414 
   415 	if (_iter == m_Deps.end())
   416 	{
   417 		return false;
   418 	}
   419 
   420 	_iter++;
   421 
   422 	if (pOwner)
   423 	{
   424 		*pOwner = (*_iter).owner;
   425 	}
   426 	if (pInterface)
   427 	{
   428 		*pInterface = (*_iter).iface;
   429 	}
   430 
   431 	*pIter = _iter;
   432 
   433 	if (_iter == m_Deps.end())
   434 	{
   435 		return false;
   436 	}
   437 
   438 	return true;
   439 }
   440 
   441 void CExtension::FreeDependencyIterator(ITERATOR *iter)
   442 {
   443 	List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
   444 
   445 	delete pIter;
   446 }
   447 
   448 void CExtension::AddInterface(SMInterface *pInterface)
   449 {
   450 	m_Interfaces.push_back(pInterface);
   451 }
   452 
   453 bool CExtension::IsRunning(char *error, size_t maxlength)
   454 {
   455 	if (!IsLoaded())
   456 	{
   457 		if (error)
   458 		{
   459 			snprintf(error, maxlength, "%s", m_Error.c_str());
   460 		}
   461 		return false;
   462 	}
   463 
   464 	return m_pAPI->QueryRunning(error, maxlength);
   465 }
   466 
   467 void CExtension::AddLibrary(const char *library)
   468 {
   469 	m_Libraries.push_back(library);
   470 }
   471 
   472 /*********************
   473  * EXTENSION MANAGER *
   474  *********************/
   475 
   476 void CExtensionManager::OnSourceModAllInitialized()
   477 {
   478 	g_ExtType = g_ShareSys.CreateIdentType("EXTENSION");
   479 	g_PluginSys.AddPluginsListener(this);
   480 	g_RootMenu.AddRootConsoleCommand("exts", "Manage extensions", this);
   481 	g_ShareSys.AddInterface(NULL, this);
   482 }
   483 
   484 void CExtensionManager::OnSourceModShutdown()
   485 {
   486 	g_RootMenu.RemoveRootConsoleCommand("exts", this);
   487 	g_ShareSys.DestroyIdentType(g_ExtType);
   488 }
   489 
   490 void CExtensionManager::Shutdown()
   491 {
   492 	List<CExtension *>::iterator iter;
   493 
   494 	while ((iter = m_Libs.begin()) != m_Libs.end())
   495 	{
   496 		UnloadExtension((*iter));
   497 	}
   498 }
   499 
   500 void CExtensionManager::TryAutoload()
   501 {
   502 	char path[PLATFORM_MAX_PATH];
   503 
   504 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "extensions");
   505 
   506 	IDirectory *pDir = g_LibSys.OpenDirectory(path);
   507 	if (!pDir)
   508 	{
   509 		return;
   510 	}
   511 
   512 	const char *lfile;
   513 	size_t len;
   514 	while (pDir->MoreFiles())
   515 	{
   516 		if (pDir->IsEntryDirectory())
   517 		{
   518 			pDir->NextEntry();
   519 			continue;
   520 		}
   521 
   522 		lfile = pDir->GetEntryName();
   523 		len = strlen(lfile);
   524 		if (len <= 9) /* size of ".autoload" */
   525 		{
   526 			pDir->NextEntry();
   527 			continue;
   528 		}
   529 
   530 		if (strcmp(&lfile[len - 9], ".autoload") != 0)
   531 		{
   532 			pDir->NextEntry();
   533 			continue;
   534 		}
   535 
   536 		char file[PLATFORM_MAX_PATH];
   537 		len = UTIL_Format(file, sizeof(file), "%s", lfile);
   538 		strcpy(&file[len - 9], ".ext");
   539 
   540 		LoadAutoExtension(file);
   541 		
   542 		pDir->NextEntry();
   543 	}
   544 }
   545 
   546 IExtension *CExtensionManager::LoadAutoExtension(const char *path)
   547 {
   548 	/* Remove platform extension if it's there. Compat hack. */
   549 	const char *ext = g_LibSys.GetFileExtension(path);
   550 	if (strcmp(ext, PLATFORM_LIB_EXT) == 0)
   551 	{
   552 		char path2[PLATFORM_MAX_PATH];
   553 		UTIL_Format(path2, sizeof(path2), "%s", path);
   554 		path2[strlen(path) - strlen(PLATFORM_LIB_EXT) - 1] = '\0';
   555 		return LoadAutoExtension(path2);
   556 	}
   557 
   558 	IExtension *pAlready;
   559 	if ((pAlready=FindExtensionByFile(path)) != NULL)
   560 	{
   561 		return pAlready;
   562 	}
   563 
   564 	char error[256];
   565 	CExtension *p = new CLocalExtension(path);
   566 
   567 	/* We put us in the list beforehand so extensions that check for each other
   568 	 * won't recursively load each other.
   569 	 */
   570 	m_Libs.push_back(p);
   571 
   572 	if (!p->Load(error, sizeof(error)) || !p->IsLoaded())
   573 	{
   574 		g_Logger.LogError("[SM] Unable to load extension \"%s\": %s", path, error);
   575 		p->SetError(error);
   576 	}
   577 
   578 	return p;
   579 }
   580 
   581 IExtension *CExtensionManager::FindExtensionByFile(const char *file)
   582 {
   583 	List<CExtension *>::iterator iter;
   584 	CExtension *pExt;
   585 
   586 	/* Chomp off the path */
   587 	char lookup[PLATFORM_MAX_PATH];
   588 	g_LibSys.GetFileFromPath(lookup, sizeof(lookup), file);
   589 
   590 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   591 	{
   592 		pExt = (*iter);
   593 		if (pExt->IsSameFile(lookup))
   594 		{
   595 			return pExt;
   596 		}
   597 	}
   598 
   599 	return NULL;
   600 }
   601 
   602 IExtension *CExtensionManager::FindExtensionByName(const char *ext)
   603 {
   604 	List<CExtension *>::iterator iter;
   605 	CExtension *pExt;
   606 	IExtensionInterface *pAPI;
   607 	const char *name;
   608 
   609 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   610 	{
   611 		pExt = (*iter);
   612 		if (!pExt->IsLoaded())
   613 		{
   614 			continue;
   615 		}
   616 		if ((pAPI = pExt->GetAPI()) == NULL)
   617 		{
   618 			continue;
   619 		}
   620 		name = pAPI->GetExtensionName();
   621 		if (!name)
   622 		{
   623 			continue;
   624 		}
   625 		if (strcmp(name, ext) == 0)
   626 		{
   627 			return pExt;
   628 		}
   629 	}
   630 
   631 	return NULL;
   632 }
   633 
   634 IExtension *CExtensionManager::LoadExtension(const char *file, char *error, size_t maxlength)
   635 {
   636 	/* Remove platform extension if it's there. Compat hack. */
   637 	const char *ext = g_LibSys.GetFileExtension(file);
   638 	if (strcmp(ext, PLATFORM_LIB_EXT) == 0)
   639 	{
   640 		char path2[PLATFORM_MAX_PATH];
   641 		UTIL_Format(path2, sizeof(path2), "%s", file);
   642 		path2[strlen(file) - strlen(PLATFORM_LIB_EXT) - 1] = '\0';
   643 		return LoadExtension(path2, error, maxlength);
   644 	}
   645 
   646 	IExtension *pAlready;
   647 	if ((pAlready=FindExtensionByFile(file)) != NULL)
   648 	{
   649 		return pAlready;
   650 	}
   651 
   652 	CExtension *pExt = new CLocalExtension(file);
   653 
   654 	if (!pExt->Load(error, maxlength) || !pExt->IsLoaded())
   655 	{
   656 		pExt->Unload();
   657 		delete pExt;
   658 		return NULL;
   659 	}
   660 
   661 	/* :TODO: do QueryRunning check if the map is loaded */
   662 
   663 	m_Libs.push_back(pExt);
   664 
   665 	return pExt;
   666 }
   667 
   668 void CExtensionManager::BindDependency(IExtension *pRequester, IfaceInfo *pInfo)
   669 {
   670 	CExtension *pExt = (CExtension *)pRequester;
   671 	CExtension *pOwner = (CExtension *)pInfo->owner;
   672 
   673 	pExt->AddDependency(pInfo);
   674 
   675 	IExtensionInterface *pAPI = pExt->GetAPI();
   676 	if (pAPI && !pAPI->QueryInterfaceDrop(pInfo->iface))
   677 	{
   678 		pOwner->AddChildDependent(pExt, pInfo->iface);
   679 	}
   680 }
   681 
   682 void CExtensionManager::AddRawDependency(IExtension *ext, IdentityToken_t *other, void *iface)
   683 {
   684 	CExtension *pExt = (CExtension *)ext;
   685 	CExtension *pOwner = GetExtensionFromIdent(other);
   686 
   687 	IfaceInfo info;
   688 
   689 	info.iface = (SMInterface *)iface;
   690 	info.owner = pOwner;
   691 
   692 	pExt->AddDependency(&info);
   693 	pOwner->AddChildDependent(pExt, (SMInterface *)iface);
   694 }
   695 
   696 void CExtensionManager::AddInterface(IExtension *pOwner, SMInterface *pInterface)
   697 {
   698 	CExtension *pExt = (CExtension *)pOwner;
   699 
   700 	pExt->AddInterface(pInterface);
   701 }
   702 
   703 void CExtensionManager::BindChildPlugin( IExtension *pParent, CPlugin *pPlugin )
   704 {
   705 	CExtension *pExt = (CExtension *)pParent;
   706 
   707 	pExt->AddPlugin(pPlugin);
   708 }
   709 
   710 void CExtensionManager::OnPluginDestroyed(IPlugin *plugin)
   711 {
   712 	List<CExtension *>::iterator iter;
   713 
   714 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   715 	{
   716 		(*iter)->DropRefsTo((CPlugin *)plugin);
   717 	}
   718 }
   719 
   720 CExtension *CExtensionManager::FindByOrder(unsigned int num)
   721 {
   722 	if (num < 1 || num > m_Libs.size())
   723 	{
   724 		return NULL;
   725 	}
   726 
   727 	List<CExtension *>::iterator iter = m_Libs.begin();
   728 
   729 	while (iter != m_Libs.end())
   730 	{
   731 		if (--num == 0)
   732 		{
   733 			return (*iter);
   734 		}
   735 		iter++;
   736 	}
   737 
   738 	return NULL;
   739 }
   740 
   741 bool CExtensionManager::UnloadExtension(IExtension *_pExt)
   742 {
   743 	if (!_pExt)
   744 	{
   745 		return false;
   746 	}
   747 
   748 	CExtension *pExt = (CExtension *)_pExt;
   749 
   750 	if (m_Libs.find(pExt) == m_Libs.end())
   751 	{
   752 		return false;
   753 	}
   754 
   755 	/* First remove us from internal lists */
   756 	g_ShareSys.RemoveInterfaces(_pExt);
   757 	m_Libs.remove(pExt);
   758 
   759 	List<CExtension *> UnloadQueue;
   760 
   761 	/* Handle dependencies */
   762 	if (pExt->IsLoaded())
   763 	{
   764 		/* Unload any dependent plugins */
   765 		List<CPlugin *>::iterator p_iter = pExt->m_Dependents.begin();
   766 		while (p_iter != pExt->m_Dependents.end())
   767 		{
   768 			/* We have to manually unlink ourselves here, since we're no longer being managed */
   769 			g_PluginSys.UnloadPlugin((*p_iter));
   770 			p_iter = pExt->m_Dependents.erase(p_iter);
   771 		}
   772 
   773 		List<String>::iterator s_iter;
   774 		for (s_iter = pExt->m_Libraries.begin();
   775 			 s_iter != pExt->m_Libraries.end();
   776 			 s_iter++)
   777 		{
   778 			g_PluginSys.OnLibraryAction((*s_iter).c_str(), false, true);
   779 		}
   780 
   781 		/* Notify and/or unload all dependencies */
   782 		List<CExtension *>::iterator c_iter;
   783 		CExtension *pDep;
   784 		IExtensionInterface *pAPI;
   785 		for (c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
   786 		{
   787 			pDep = (*c_iter);
   788 			if ((pAPI=pDep->GetAPI()) == NULL)
   789 			{
   790 				continue;
   791 			}
   792 			if (pDep == pExt)
   793 			{
   794 				continue;
   795 			}
   796 			/* Now, get its dependency list */
   797 			bool dropped = false;
   798 			List<IfaceInfo>::iterator i_iter = pDep->m_Deps.begin();
   799 			while (i_iter != pDep->m_Deps.end())
   800 			{
   801 				if ((*i_iter).owner == _pExt)
   802 				{
   803 					if (!pAPI->QueryInterfaceDrop((*i_iter).iface))
   804 					{
   805 						if (!dropped)
   806 						{
   807 							dropped = true;
   808 							UnloadQueue.push_back(pDep);
   809 						}
   810 					}
   811 					pAPI->NotifyInterfaceDrop((*i_iter).iface);
   812 					i_iter = pDep->m_Deps.erase(i_iter);
   813 				}
   814 				else
   815 				{
   816 					i_iter++;
   817 				}
   818 			}
   819 			/* Flush out any back references to this plugin */
   820 			i_iter = pDep->m_ChildDeps.begin();
   821 			while (i_iter != pDep->m_ChildDeps.end())
   822 			{
   823 				if ((*i_iter).owner == pExt)
   824 				{
   825 					i_iter = pDep->m_ChildDeps.erase(i_iter);
   826 				}
   827 				else
   828 				{
   829 					i_iter++;
   830 				}
   831 			}
   832 		}
   833 
   834 		/* Unbind our natives from Core */
   835 		pExt->DropEverything();
   836 	}
   837 
   838 	IdentityToken_t *pIdentity;
   839 	if ((pIdentity = pExt->GetIdentity()) != NULL)
   840 	{
   841 		SMGlobalClass *glob = SMGlobalClass::head;
   842 		while (glob)
   843 		{
   844 			glob->OnSourceModIdentityDropped(pIdentity);
   845 			glob = glob->m_pGlobalClassNext;
   846 		}
   847 	}
   848 
   849 	/* Tell it to unload */
   850 	if (pExt->IsLoaded())
   851 	{
   852 		IExtensionInterface *pAPI = pExt->GetAPI();
   853 		pAPI->OnExtensionUnload();
   854 	}
   855 
   856 	pExt->Unload();
   857 	delete pExt;
   858 
   859 	List<CExtension *>::iterator iter;
   860 	for (iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
   861 	{
   862 		/* NOTE: This is safe because the unload function backs out of anything not present */
   863 		UnloadExtension((*iter));
   864 	}
   865 
   866 	return true;
   867 }
   868 
   869 void CExtensionManager::MarkAllLoaded()
   870 {
   871 	List<CExtension *>::iterator iter;
   872 	CExtension *pExt;
   873 
   874 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   875 	{
   876 		pExt = (*iter);
   877 		if (!pExt->IsLoaded())
   878 		{
   879 			continue;
   880 		}
   881 		if (pExt->m_bFullyLoaded)
   882 		{
   883 			continue;
   884 		}
   885 		pExt->MarkAllLoaded();
   886 	}
   887 }
   888 
   889 void CExtensionManager::AddDependency(IExtension *pSource, const char *file, bool required, bool autoload)
   890 {
   891 	/* This function doesn't really need to do anything now.  We make sure the 
   892 	 * other extension is loaded, but handling of dependencies is really done 
   893 	 * by the interface fetcher.
   894 	 */
   895 	if (required || autoload)
   896 	{
   897 		LoadAutoExtension(file);
   898 	}
   899 }
   900 
   901 void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
   902 {
   903 	int argcount = command.ArgC();
   904 	if (argcount >= 3)
   905 	{
   906 		const char *cmd = command.Arg(2);
   907 		if (strcmp(cmd, "list") == 0)
   908 		{
   909 			List<CExtension *>::iterator iter;
   910 			CExtension *pExt;
   911 			unsigned int num = 1;
   912 			switch (m_Libs.size())
   913 			{
   914 			case 1:
   915 				{
   916 					g_RootMenu.ConsolePrint("[SM] Displaying 1 extension:");
   917 					break;
   918 				}
   919 			case 0:
   920 				{
   921 					g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
   922 					break;
   923 				}
   924 			default:
   925 				{
   926 					g_RootMenu.ConsolePrint("[SM] Displaying %d extensions:", m_Libs.size());
   927 					break;
   928 				}
   929 			}
   930 			for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++,num++)
   931 			{
   932 				pExt = (*iter);
   933 				if (pExt->IsLoaded())
   934 				{
   935 					char error[255];
   936 					if (!pExt->IsRunning(error, sizeof(error)))
   937 					{
   938 						g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), error);
   939 					}
   940 					else
   941 					{
   942 						IExtensionInterface *pAPI = pExt->GetAPI();
   943 						const char *name = pAPI->GetExtensionName();
   944 						const char *version = pAPI->GetExtensionVerString();
   945 						const char *descr = pAPI->GetExtensionDescription();
   946 						g_RootMenu.ConsolePrint("[%02d] %s (%s): %s", num, name, version, descr);
   947 					}
   948 				} else {
   949 					g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), pExt->m_Error.c_str());
   950 				}
   951 			}
   952 			return;
   953 		}
   954 		else if (strcmp(cmd, "load") == 0)
   955 		{
   956 			if (argcount < 4)
   957 			{
   958 				g_RootMenu.ConsolePrint("[SM] Usage: sm exts load <file>");
   959 				return;
   960 			}
   961 
   962 			const char *filename = command.Arg(3);
   963 			char path[PLATFORM_MAX_PATH];
   964 			char error[256];
   965 
   966 			UTIL_Format(path, sizeof(path), "%s%s%s", filename, !strstr(filename, ".ext") ? ".ext" : "",
   967 				!strstr(filename, "." PLATFORM_LIB_EXT) ? "." PLATFORM_LIB_EXT : "");
   968 			
   969 			if (FindExtensionByFile(path) != NULL)
   970 			{
   971 				g_RootMenu.ConsolePrint("[SM] Extension %s is already loaded.", path);
   972 				return;
   973 			}
   974 			
   975 			if (LoadExtension(path, error, sizeof(error)))
   976 			{
   977 				g_RootMenu.ConsolePrint("[SM] Loaded extension %s successfully.", path);
   978 			} else
   979 			{
   980 				g_RootMenu.ConsolePrint("[SM] Extension %s failed to load: %s", path, error);
   981 			}
   982 			
   983 			return;
   984 		}
   985 		else if (strcmp(cmd, "info") == 0)
   986 		{
   987 			if (argcount < 4)
   988 			{
   989 				g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
   990 				return;
   991 			}
   992 
   993 			const char *sId = command.Arg(3);
   994 			unsigned int id = atoi(sId);
   995 			if (id <= 0)
   996 			{
   997 				g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
   998 				return;
   999 			}
  1000 
  1001 			if (m_Libs.size() == 0)
  1002 			{
  1003 				g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
  1004 				return;
  1005 			}
  1006 
  1007 			if (id > m_Libs.size())
  1008 			{
  1009 				g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
  1010 				return;
  1011 			}
  1012 
  1013 			List<CExtension *>::iterator iter = m_Libs.begin();
  1014 			CExtension *pExt = NULL;
  1015 			while (iter != m_Libs.end())
  1016 			{
  1017 				if (--id == 0)
  1018 				{
  1019 					pExt = (*iter);
  1020 					break;
  1021 				}
  1022 				iter++;
  1023 			}
  1024 			/* This should never happen */
  1025 			if (!pExt)
  1026 			{
  1027 				g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
  1028 				return;
  1029 			}
  1030 
  1031 			if (!pExt->IsLoaded())
  1032 			{
  1033 				g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
  1034 				g_RootMenu.ConsolePrint(" Loaded: No (%s)", pExt->m_Error.c_str());
  1035 			}
  1036 			else
  1037 			{
  1038 				char error[255];
  1039 				if (!pExt->IsRunning(error, sizeof(error)))
  1040 				{
  1041 					g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
  1042 					g_RootMenu.ConsolePrint(" Loaded: Yes");
  1043 					g_RootMenu.ConsolePrint(" Running: No (%s)", error);
  1044 				}
  1045 				else
  1046 				{
  1047 					IExtensionInterface *pAPI = pExt->GetAPI();
  1048 					g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
  1049 					g_RootMenu.ConsolePrint(" Loaded: Yes (version %s)", pAPI->GetExtensionVerString());
  1050 					g_RootMenu.ConsolePrint(" Name: %s (%s)", pAPI->GetExtensionName(), pAPI->GetExtensionDescription());
  1051 					g_RootMenu.ConsolePrint(" Author: %s (%s)", pAPI->GetExtensionAuthor(), pAPI->GetExtensionURL());
  1052 					g_RootMenu.ConsolePrint(" Binary info: API version %d (compiled %s)", pAPI->GetExtensionVersion(), pAPI->GetExtensionDateString());
  1053 
  1054 					if (pExt->IsExternal())
  1055 					{
  1056 						g_RootMenu.ConsolePrint(" Method: Loaded by Metamod:Source, attached to SourceMod");
  1057 					}
  1058 					else if (pAPI->IsMetamodExtension())
  1059 					{
  1060 						g_RootMenu.ConsolePrint(" Method: Loaded by SourceMod, attached to Metamod:Source");
  1061 					}
  1062 					else
  1063 					{
  1064 						g_RootMenu.ConsolePrint(" Method: Loaded by SourceMod");
  1065 					}
  1066 				}
  1067 			}
  1068 			return;
  1069 		}
  1070 		else if (strcmp(cmd, "unload") == 0)
  1071 		{
  1072 			if (argcount < 4)
  1073 			{
  1074 				g_RootMenu.ConsolePrint("[SM] Usage: sm unload <#> [code]");
  1075 				return;
  1076 			}
  1077 
  1078 			const char *arg = command.Arg(3);
  1079 			unsigned int num = atoi(arg);
  1080 			CExtension *pExt = FindByOrder(num);
  1081 
  1082 			if (!pExt)
  1083 			{
  1084 				g_RootMenu.ConsolePrint("[SM] Extension number %d was not found.", num);
  1085 				return;
  1086 			}
  1087 
  1088 			if (argcount > 4 && pExt->unload_code)
  1089 			{
  1090 				const char *unload = command.Arg(4);
  1091 				if (pExt->unload_code == (unsigned)atoi(unload))
  1092 				{
  1093 					char filename[PLATFORM_MAX_PATH];
  1094 					snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
  1095 					UnloadExtension(pExt);
  1096 					g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
  1097 				}
  1098 				else
  1099 				{
  1100 					g_RootMenu.ConsolePrint("[SM] Please try again, the correct unload code is \"%d\"", pExt->unload_code);
  1101 				}
  1102 				return;
  1103 			}
  1104 
  1105 			if (!pExt->IsLoaded() 
  1106 				|| (!pExt->m_ChildDeps.size() && !pExt->m_Dependents.size()))
  1107 			{
  1108 				char filename[PLATFORM_MAX_PATH];
  1109 				snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
  1110 				UnloadExtension(pExt);
  1111 				g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
  1112 				return;
  1113 			}
  1114 			else
  1115 			{
  1116 				List<CPlugin *> plugins;
  1117 				if (pExt->m_ChildDeps.size())
  1118 				{
  1119 					g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename());
  1120 					List<CExtension *>::iterator iter;
  1121 					CExtension *pOther;
  1122 					/* Get list of all extensions */
  1123 					for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
  1124 					{
  1125 						List<IfaceInfo>::iterator i_iter;
  1126 						pOther = (*iter);
  1127 						if (!pOther->IsLoaded() || pOther == pExt)
  1128 						{
  1129 							continue;
  1130 						}
  1131 						/* Get their dependencies */
  1132 						for (i_iter=pOther->m_Deps.begin();
  1133 							 i_iter!=pOther->m_Deps.end();
  1134 							 i_iter++)
  1135 						{
  1136 							/* Is this dependency to us? */
  1137 							if ((*i_iter).owner != pExt)
  1138 							{
  1139 								continue;
  1140 							}
  1141 							/* Will our dependent care? */
  1142 							if (!pExt->GetAPI()->QueryInterfaceDrop((*i_iter).iface))
  1143 							{
  1144 								g_RootMenu.ConsolePrint(" -> %s", pExt->GetFilename());
  1145 								/* Add to plugin unload list */
  1146 								List<CPlugin *>::iterator p_iter;
  1147 								for (p_iter=pOther->m_Dependents.begin();
  1148 									 p_iter!=pOther->m_Dependents.end();
  1149 									 p_iter++)
  1150 								{
  1151 									if (plugins.find((*p_iter)) == plugins.end())
  1152 									{
  1153 										plugins.push_back((*p_iter));
  1154 									}
  1155 								}
  1156 							}
  1157 						}
  1158 					}
  1159 				}
  1160 				if (pExt->m_Dependents.size())
  1161 				{
  1162 					g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename());
  1163 					List<CPlugin *>::iterator iter;
  1164 					CPlugin *pPlugin;
  1165 					for (iter = pExt->m_Dependents.begin(); iter != pExt->m_Dependents.end(); iter++)
  1166 					{
  1167 						pPlugin = (*iter);
  1168 						if (plugins.find(pPlugin) == plugins.end())
  1169 						{
  1170 							plugins.push_back(pPlugin);
  1171 						}
  1172 					}
  1173 					for (iter = plugins.begin(); iter != plugins.end(); iter++)
  1174 					{
  1175 						pPlugin = (*iter);
  1176 						g_RootMenu.ConsolePrint(" -> %s", pPlugin->GetFilename());
  1177 					}
  1178 				}
  1179 				srand(static_cast<int>(time(NULL)));
  1180 				pExt->unload_code = (rand() % 877) + 123;	//123 to 999
  1181 				g_RootMenu.ConsolePrint("[SM] To verify unloading %s, please use the following: ", pExt->GetFilename());
  1182 				g_RootMenu.ConsolePrint("[SM] sm exts unload %d %d", num, pExt->unload_code);
  1183 
  1184 				return;
  1185 			}
  1186 		}
  1187 		else if (strcmp(cmd, "reload") == 0)
  1188 		{
  1189 			if (argcount < 4)
  1190 			{
  1191 				g_RootMenu.ConsolePrint("[SM] Usage: sm exts reload <#>");
  1192 				return;
  1193 			}
  1194 			
  1195 			const char *arg = command.Arg(3);
  1196 			unsigned int num = atoi(arg);
  1197 			CExtension *pExt = FindByOrder(num);
  1198 
  1199 			if (!pExt)
  1200 			{
  1201 				g_RootMenu.ConsolePrint("[SM] Extension number %d was not found.", num);
  1202 				return;
  1203 			}
  1204 			
  1205 			if (pExt->IsLoaded())
  1206 			{
  1207 				char filename[PLATFORM_MAX_PATH];
  1208 				char error[255];
  1209 				
  1210 				snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
  1211 				
  1212 				if (pExt->Reload(error, sizeof(error)))
  1213 				{
  1214 					g_RootMenu.ConsolePrint("[SM] Extension %s is now reloaded.", filename);
  1215 				}
  1216 				else
  1217 				{
  1218 					g_RootMenu.ConsolePrint("[SM] Extension %s failed to reload: %s", filename, error);
  1219 				}
  1220 					
  1221 				return;
  1222 			} 
  1223 			else
  1224 			{
  1225 				g_RootMenu.ConsolePrint("[SM] Extension %s is not loaded.", pExt->GetFilename());
  1226 				
  1227 				return;
  1228 			}
  1229 			
  1230 		}
  1231 	}
  1232 
  1233 	g_RootMenu.ConsolePrint("SourceMod Extensions Menu:");
  1234 	g_RootMenu.DrawGenericOption("info", "Extra extension information");
  1235 	g_RootMenu.DrawGenericOption("list", "List extensions");
  1236 	g_RootMenu.DrawGenericOption("load", "Load an extension");
  1237 	g_RootMenu.DrawGenericOption("reload", "Reload an extension");
  1238 	g_RootMenu.DrawGenericOption("unload", "Unload an extension");
  1239 }
  1240 
  1241 CExtension *CExtensionManager::GetExtensionFromIdent(IdentityToken_t *ptr)
  1242 {
  1243 	if (ptr->type == g_ExtType)
  1244 	{
  1245 		return (CExtension *)(ptr->ptr);
  1246 	}
  1247 
  1248 	return NULL;
  1249 }
  1250 
  1251 CExtensionManager::CExtensionManager()
  1252 {
  1253 }
  1254 
  1255 CExtensionManager::~CExtensionManager()
  1256 {
  1257 }
  1258 
  1259 void CExtensionManager::AddLibrary(IExtension *pSource, const char *library)
  1260 {
  1261 	CExtension *pExt = (CExtension *)pSource;
  1262 	pExt->AddLibrary(library);
  1263 	g_PluginSys.OnLibraryAction(library, false, false);
  1264 }
  1265 
  1266 bool CExtensionManager::LibraryExists(const char *library)
  1267 {
  1268 	CExtension *pExt;
  1269 
  1270 	for (List<CExtension *>::iterator iter = m_Libs.begin();
  1271 		 iter != m_Libs.end();
  1272 		 iter++)
  1273 	{
  1274 		pExt = (*iter);
  1275 		for (List<String>::iterator s_iter = pExt->m_Libraries.begin();
  1276 			 s_iter != pExt->m_Libraries.end();
  1277 			 s_iter++)
  1278 		{
  1279 			if ((*s_iter).compare(library) == 0)
  1280 			{
  1281 				return true;
  1282 			}
  1283 		}
  1284 	}
  1285 
  1286 	return false;
  1287 }
  1288 
  1289 IExtension *CExtensionManager::LoadExternal(IExtensionInterface *pInterface,
  1290 											const char *filepath,
  1291 											const char *filename,
  1292 											char *error,
  1293 											size_t maxlength)
  1294 {
  1295 	IExtension *pAlready;
  1296 	if ((pAlready=FindExtensionByFile(filename)) != NULL)
  1297 	{
  1298 		return pAlready;
  1299 	}
  1300 
  1301 	CExtension *pExt = new CRemoteExtension(pInterface, filename, filepath);
  1302 
  1303 	if (!pExt->Load(error, maxlength) || !pExt->IsLoaded())
  1304 	{
  1305 		pExt->Unload();
  1306 		delete pExt;
  1307 		return NULL;
  1308 	}
  1309 
  1310 	m_Libs.push_back(pExt);
  1311 
  1312 	return pExt;
  1313 }
  1314 
  1315 void CExtensionManager::CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax)
  1316 {
  1317 	IExtensionInterface *pAPI;
  1318 	List<CExtension *>::iterator iter;
  1319 
  1320 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
  1321 	{
  1322 		if ((pAPI = (*iter)->GetAPI()) == NULL)
  1323 		{
  1324 			continue;
  1325 		}
  1326 		if (pAPI->GetExtensionVersion() > 3)
  1327 		{
  1328 			pAPI->OnCoreMapStart(pEdictList, edictCount, clientMax);
  1329 		}
  1330 	}
  1331 }
  1332 
  1333 bool CLocalExtension::IsSameFile(const char *file)
  1334 {
  1335 	/* Only care about the shortened name. */
  1336 	return strcmp(file, m_File.c_str()) == 0;
  1337 }
  1338 
  1339 bool CRemoteExtension::IsSameFile(const char *file)
  1340 {
  1341 	/* :TODO: this could be better, but no one uses this API anyway. */
  1342 	return strcmp(file, m_Path.c_str()) == 0;
  1343 }
  1344