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