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