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