core/systems/ExtensionSys.cpp
author David Anderson <dvander@alliedmods.net>
Mon Oct 15 00:38:25 2007 +0000 (2007-10-15)
changeset 1568 ecbaee393b0b
parent 1541 e46ad208b9b4
child 1572 adbc41dc9cd0
permissions -rw-r--r--
extensions can now be built for multiple engines, and will autoload from auto.X.Y folders
     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 /*********************
   344  * EXTENSION MANAGER *
   345  *********************/
   346 
   347 void CExtensionManager::OnSourceModAllInitialized()
   348 {
   349 	g_ExtType = g_ShareSys.CreateIdentType("EXTENSION");
   350 	g_PluginSys.AddPluginsListener(this);
   351 	g_RootMenu.AddRootConsoleCommand("exts", "Manage extensions", this);
   352 	g_ShareSys.AddInterface(NULL, this);
   353 }
   354 
   355 void CExtensionManager::OnSourceModShutdown()
   356 {
   357 	g_RootMenu.RemoveRootConsoleCommand("exts", this);
   358 	g_ShareSys.DestroyIdentType(g_ExtType);
   359 }
   360 
   361 void CExtensionManager::Shutdown()
   362 {
   363 	List<CExtension *>::iterator iter;
   364 
   365 	while ((iter = m_Libs.begin()) != m_Libs.end())
   366 	{
   367 		UnloadExtension((*iter));
   368 	}
   369 }
   370 
   371 void CExtensionManager::TryAutoload()
   372 {
   373 	char path[PLATFORM_MAX_PATH];
   374 
   375 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "extensions");
   376 
   377 	IDirectory *pDir = g_LibSys.OpenDirectory(path);
   378 	if (!pDir)
   379 	{
   380 		return;
   381 	}
   382 
   383 	const char *lfile;
   384 	size_t len;
   385 	while (pDir->MoreFiles())
   386 	{
   387 		if (pDir->IsEntryDirectory())
   388 		{
   389 			pDir->NextEntry();
   390 			continue;
   391 		}
   392 
   393 		lfile = pDir->GetEntryName();
   394 		len = strlen(lfile);
   395 		if (len <= 9) /* size of ".autoload" */
   396 		{
   397 			pDir->NextEntry();
   398 			continue;
   399 		}
   400 
   401 		if (strcmp(&lfile[len - 9], ".autoload") != 0)
   402 		{
   403 			pDir->NextEntry();
   404 			continue;
   405 		}
   406 
   407 		char file[PLATFORM_MAX_PATH];
   408 		len = UTIL_Format(file, sizeof(file), "%s", lfile);
   409 		strcpy(&file[len - 9], ".ext." PLATFORM_LIB_EXT);
   410 
   411 		LoadAutoExtension(file);
   412 		
   413 		pDir->NextEntry();
   414 	}
   415 }
   416 
   417 IExtension *CExtensionManager::LoadAutoExtension(const char *path)
   418 {
   419 	if (!strstr(path, "." PLATFORM_LIB_EXT))
   420 	{
   421 		char newpath[PLATFORM_MAX_PATH];
   422 		g_LibSys.PathFormat(newpath, sizeof(newpath), "%s.%s", path, PLATFORM_LIB_EXT);
   423 		return LoadAutoExtension(newpath);
   424 	}
   425 
   426 	IExtension *pAlready;
   427 	if ((pAlready=FindExtensionByFile(path)) != NULL)
   428 	{
   429 		return pAlready;
   430 	}
   431 
   432 	char error[256];
   433 	CExtension *p = new CExtension(path, error, sizeof(error));
   434 
   435 	/* We put us in the list beforehand so extensions that check for each other
   436 	 * won't recursively load each other.
   437 	 */
   438 	m_Libs.push_back(p);
   439 
   440 	if (!p->Load(error, sizeof(error)) || !p->IsLoaded())
   441 	{
   442 		g_Logger.LogError("[SM] Unable to load extension \"%s\": %s", path, error);
   443 		p->SetError(error);
   444 	}
   445 
   446 	return p;
   447 }
   448 
   449 IExtension *CExtensionManager::FindExtensionByFile(const char *file)
   450 {
   451 	List<CExtension *>::iterator iter;
   452 	CExtension *pExt;
   453 
   454 	if (!strstr(file, "." PLATFORM_LIB_EXT))
   455 	{
   456 		char path[PLATFORM_MAX_PATH];
   457 		UTIL_Format(path, sizeof(path), "%s.%s", file, PLATFORM_LIB_EXT);
   458 		return FindExtensionByFile(path);
   459 	}
   460 
   461 	/* Chomp off the path */
   462 	char lookup[PLATFORM_MAX_PATH];
   463 	g_LibSys.GetFileFromPath(lookup, sizeof(lookup), file);
   464 
   465 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   466 	{
   467 		pExt = (*iter);
   468 		char short_file[PLATFORM_MAX_PATH];
   469 		g_LibSys.GetFileFromPath(short_file, sizeof(short_file), pExt->GetFilename());
   470 		if (strcmp(lookup, short_file) == 0)
   471 		{
   472 			return pExt;
   473 		}
   474 	}
   475 
   476 	return NULL;
   477 }
   478 
   479 IExtension *CExtensionManager::FindExtensionByName(const char *ext)
   480 {
   481 	List<CExtension *>::iterator iter;
   482 	CExtension *pExt;
   483 	IExtensionInterface *pAPI;
   484 	const char *name;
   485 
   486 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   487 	{
   488 		pExt = (*iter);
   489 		if (!pExt->IsLoaded())
   490 		{
   491 			continue;
   492 		}
   493 		if ((pAPI = pExt->GetAPI()) == NULL)
   494 		{
   495 			continue;
   496 		}
   497 		name = pAPI->GetExtensionName();
   498 		if (!name)
   499 		{
   500 			continue;
   501 		}
   502 		if (strcmp(name, ext) == 0)
   503 		{
   504 			return pExt;
   505 		}
   506 	}
   507 
   508 	return NULL;
   509 }
   510 
   511 IExtension *CExtensionManager::LoadExtension(const char *file, ExtensionLifetime lifetime, char *error, size_t maxlength)
   512 {
   513 	IExtension *pAlready;
   514 	if ((pAlready=FindExtensionByFile(file)) != NULL)
   515 	{
   516 		return pAlready;
   517 	}
   518 
   519 	CExtension *pExt = new CExtension(file, error, maxlength);
   520 
   521 	/* :NOTE: lifetime is currently ignored */
   522 
   523 	if (!pExt->Load(error, maxlength) || !pExt->IsLoaded())
   524 	{
   525 		delete pExt;
   526 		return NULL;
   527 	}
   528 
   529 	/* :TODO: do QueryRunning check if the map is loaded */
   530 
   531 	m_Libs.push_back(pExt);
   532 
   533 	return pExt;
   534 }
   535 
   536 void CExtensionManager::BindDependency(IExtension *pRequester, IfaceInfo *pInfo)
   537 {
   538 	CExtension *pExt = (CExtension *)pRequester;
   539 	CExtension *pOwner = (CExtension *)pInfo->owner;
   540 
   541 	pExt->AddDependency(pInfo);
   542 
   543 	IExtensionInterface *pAPI = pExt->GetAPI();
   544 	if (pAPI && !pAPI->QueryInterfaceDrop(pInfo->iface))
   545 	{
   546 		pOwner->AddChildDependent(pExt, pInfo->iface);
   547 	}
   548 }
   549 
   550 void CExtensionManager::AddInterface(IExtension *pOwner, SMInterface *pInterface)
   551 {
   552 	CExtension *pExt = (CExtension *)pOwner;
   553 
   554 	pExt->AddInterface(pInterface);
   555 }
   556 
   557 void CExtensionManager::BindChildPlugin(IExtension *pParent, IPlugin *pPlugin)
   558 {
   559 	CExtension *pExt = (CExtension *)pParent;
   560 
   561 	pExt->AddPlugin(pPlugin);
   562 }
   563 
   564 void CExtensionManager::OnPluginDestroyed(IPlugin *plugin)
   565 {
   566 	List<CExtension *>::iterator iter;
   567 
   568 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   569 	{
   570 		(*iter)->RemovePlugin(plugin);
   571 	}
   572 }
   573 
   574 CExtension *CExtensionManager::FindByOrder(unsigned int num)
   575 {
   576 	if (num < 1 || num > m_Libs.size())
   577 	{
   578 		return NULL;
   579 	}
   580 
   581 	List<CExtension *>::iterator iter = m_Libs.begin();
   582 
   583 	while (iter != m_Libs.end())
   584 	{
   585 		if (--num == 0)
   586 		{
   587 			return (*iter);
   588 		}
   589 		iter++;
   590 	}
   591 
   592 	return NULL;
   593 }
   594 
   595 void CExtensionManager::BindAllNativesToPlugin(IPlugin *pPlugin)
   596 {
   597 	IPluginContext *pContext = pPlugin->GetBaseContext();
   598 
   599 	List<CExtension *> exts;
   600 
   601 	uint32_t natives = pContext->GetNativesNum();
   602 	sp_native_t *native;
   603 	sm_extnative_t *x_native;
   604 	for (uint32_t i=0; i<natives; i++)
   605 	{
   606 		/* Make sure the native is valid */
   607 		if (pContext->GetNativeByIndex(i, &native) != SP_ERROR_NONE)
   608 		{
   609 			continue;
   610 		}
   611 		/* Make sure the native is not already bound */
   612 		if (native->status == SP_NATIVE_BOUND)
   613 		{
   614 			continue;
   615 		}
   616 		/* See if we've got this native in our cache */
   617 		if ((x_native = m_ExtNatives.retrieve(native->name)) == NULL)
   618 		{
   619 			continue;
   620 		}
   621 		/* Try and bind it */
   622 		if (pContext->BindNativeToIndex(i, x_native->info->func) != SP_ERROR_NONE)
   623 		{
   624 			continue;
   625 		}
   626 		/* See if it's optional */
   627 		if (native->flags & SP_NTVFLAG_OPTIONAL)
   628 		{
   629 			WeakNative wkn = WeakNative((CPlugin *)pPlugin, i);
   630 			x_native->owner->m_WeakNatives.push_back(wkn);
   631 		} else if (exts.find(x_native->owner) == exts.end()) {
   632 			exts.push_back(x_native->owner);
   633 		}
   634 	}
   635 
   636 	List<CExtension *>::iterator iter;
   637 	for (iter = exts.begin(); iter != exts.end(); iter++)
   638 	{
   639 		CExtension *pExt = (*iter);
   640 		if (pExt->m_Plugins.find(pPlugin) != pExt->m_Plugins.end())
   641 		{
   642 			continue;
   643 		}
   644 		pExt->m_Plugins.push_back(pPlugin);
   645 	}
   646 }
   647 
   648 bool CExtensionManager::UnloadExtension(IExtension *_pExt)
   649 {
   650 	if (!_pExt)
   651 	{
   652 		return false;
   653 	}
   654 
   655 	CExtension *pExt = (CExtension *)_pExt;
   656 
   657 	if (m_Libs.find(pExt) == m_Libs.end())
   658 	{
   659 		return false;
   660 	}
   661 
   662 	/* First remove us from internal lists */
   663 	g_ShareSys.RemoveInterfaces(_pExt);
   664 	m_Libs.remove(pExt);
   665 
   666 	List<CExtension *> UnloadQueue;
   667 
   668 	/* Handle dependencies */
   669 	if (pExt->IsLoaded())
   670 	{
   671 		/* Unload any dependent plugins */
   672 		List<IPlugin *>::iterator p_iter = pExt->m_Plugins.begin();
   673 		while (p_iter != pExt->m_Plugins.end())
   674 		{
   675 			/* We have to manually unlink ourselves here, since we're no longer being managed */
   676 			g_PluginSys.UnloadPlugin((*p_iter));
   677 			p_iter = pExt->m_Plugins.erase(p_iter);
   678 		}
   679 
   680 		/* Unbound weak natives */
   681 		List<WeakNative>::iterator wkn_iter;
   682 		for (wkn_iter=pExt->m_WeakNatives.begin(); wkn_iter!=pExt->m_WeakNatives.end(); wkn_iter++)
   683 		{
   684 			WeakNative & wkn = (*wkn_iter);
   685 			sp_context_t *ctx = wkn.pl->GetContext();
   686 			ctx->natives[wkn.idx].status = SP_NATIVE_UNBOUND;
   687 		}
   688 
   689 		/* Notify and/or unload all dependencies */
   690 		List<CExtension *>::iterator c_iter;
   691 		CExtension *pDep;
   692 		IExtensionInterface *pAPI;
   693 		for (c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
   694 		{
   695 			pDep = (*c_iter);
   696 			if ((pAPI=pDep->GetAPI()) == NULL)
   697 			{
   698 				continue;
   699 			}
   700 			if (pDep == pExt)
   701 			{
   702 				continue;
   703 			}
   704 			/* Now, get its dependency list */
   705 			bool dropped = false;
   706 			List<IfaceInfo>::iterator i_iter = pDep->m_Deps.begin();
   707 			while (i_iter != pDep->m_Deps.end())
   708 			{
   709 				if ((*i_iter).owner == _pExt)
   710 				{
   711 					if (!pAPI->QueryInterfaceDrop((*i_iter).iface))
   712 					{
   713 						if (!dropped)
   714 						{
   715 							dropped = true;
   716 							UnloadQueue.push_back(pDep);
   717 						}
   718 					}
   719 					pAPI->NotifyInterfaceDrop((*i_iter).iface);
   720 					i_iter = pDep->m_Deps.erase(i_iter);
   721 				} else {
   722 					i_iter++;
   723 				}
   724 			}
   725 			/* Flush out any back references to this plugin */
   726 			i_iter = pDep->m_ChildDeps.begin();
   727 			while (i_iter != pDep->m_ChildDeps.end())
   728 			{
   729 				if ((*i_iter).owner == pExt)
   730 				{
   731 					i_iter = pDep->m_ChildDeps.erase(i_iter);
   732 				} else {
   733 					i_iter++;
   734 				}
   735 			}
   736 		}
   737 
   738 		/* Unbind our natives from Core */
   739 		List<const sp_nativeinfo_t *>::iterator native_iter;
   740 		for (native_iter = pExt->m_Natives.begin();
   741 			 native_iter != pExt->m_Natives.end();
   742 			 native_iter++)
   743 		{
   744 			const sp_nativeinfo_t *natives = (*native_iter);
   745 			sm_extnative_t *x_native;
   746 			for (unsigned int n = 0;
   747 				 natives[n].name != NULL && natives[n].func != NULL;
   748 				 n++)
   749 			{
   750 				x_native = m_ExtNatives.retrieve(natives[n].name);
   751 				if (x_native && x_native->owner == pExt)
   752 				{
   753 					m_ExtNatives.remove(natives[n].name);
   754 				}
   755 			}
   756 		}
   757 
   758 		/* Tell it to unload */
   759 		pAPI = pExt->GetAPI();
   760 		pAPI->OnExtensionUnload();
   761 	}
   762 
   763 	IdentityToken_t *pIdentity;
   764 	if ((pIdentity = pExt->GetIdentity()) != NULL)
   765 	{
   766 		SMGlobalClass *glob = SMGlobalClass::head;
   767 		while (glob)
   768 		{
   769 			glob->OnSourceModIdentityDropped(pIdentity);
   770 			glob = glob->m_pGlobalClassNext;
   771 		}
   772 	}
   773 
   774 	delete pExt;
   775 
   776 	List<CExtension *>::iterator iter;
   777 	for (iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
   778 	{
   779 		/* NOTE: This is safe because the unload function backs out of anything not present */
   780 		UnloadExtension((*iter));
   781 	}
   782 
   783 	return true;
   784 }
   785 
   786 void CExtensionManager::AddNatives(IExtension *pOwner, const sp_nativeinfo_t *natives)
   787 {
   788 	CExtension *pExt = (CExtension *)pOwner;
   789 
   790 	pExt->m_Natives.push_back(natives);
   791 
   792 	for (unsigned int i = 0; natives[i].func != NULL && natives[i].name != NULL; i++)
   793 	{
   794 		if (m_ExtNatives.retrieve(natives[i].name) != NULL)
   795 		{
   796 			continue;
   797 		}
   798 		sm_extnative_t x_native;
   799 		x_native.info = &natives[i];
   800 		x_native.owner = pExt;
   801 		m_ExtNatives.insert(natives[i].name, x_native);
   802 	}
   803 }
   804 
   805 void CExtensionManager::MarkAllLoaded()
   806 {
   807 	List<CExtension *>::iterator iter;
   808 	CExtension *pExt;
   809 
   810 	for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
   811 	{
   812 		pExt = (*iter);
   813 		if (!pExt->IsLoaded())
   814 		{
   815 			continue;
   816 		}
   817 		if (pExt->m_FullyLoaded)
   818 		{
   819 			continue;
   820 		}
   821 		pExt->MarkAllLoaded();
   822 	}
   823 }
   824 
   825 void CExtensionManager::AddDependency(IExtension *pSource, const char *file, bool required, bool autoload)
   826 {
   827 	/* This function doesn't really need to do anything now.  We make sure the 
   828 	 * other extension is loaded, but handling of dependencies is really done 
   829 	 * by the interface fetcher.
   830 	 */
   831 	if (required || autoload)
   832 	{
   833 		LoadAutoExtension(file);
   834 	}
   835 }
   836 
   837 void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
   838 {
   839 	int argcount = command.ArgC();
   840 	if (argcount >= 3)
   841 	{
   842 		const char *cmd = command.Arg(2);
   843 		if (strcmp(cmd, "list") == 0)
   844 		{
   845 			List<CExtension *>::iterator iter;
   846 			CExtension *pExt;
   847 			unsigned int num = 1;
   848 			switch (m_Libs.size())
   849 			{
   850 			case 1:
   851 				{
   852 					g_RootMenu.ConsolePrint("[SM] Displaying 1 extension:");
   853 					break;
   854 				}
   855 			case 0:
   856 				{
   857 					g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
   858 					break;
   859 				}
   860 			default:
   861 				{
   862 					g_RootMenu.ConsolePrint("[SM] Displaying %d extensions:", m_Libs.size());
   863 					break;
   864 				}
   865 			}
   866 			for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++,num++)
   867 			{
   868 				pExt = (*iter);
   869 				if (pExt->IsLoaded())
   870 				{
   871 					char error[255];
   872 					if (!pExt->IsRunning(error, sizeof(error)))
   873 					{
   874 						g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), error);
   875 					} else {
   876 						IExtensionInterface *pAPI = pExt->GetAPI();
   877 						const char *name = pAPI->GetExtensionName();
   878 						const char *version = pAPI->GetExtensionVerString();
   879 						const char *descr = pAPI->GetExtensionDescription();
   880 						g_RootMenu.ConsolePrint("[%02d] %s (%s): %s", num, name, version, descr);
   881 					}
   882 				} else {
   883 					g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), pExt->m_Error.c_str());
   884 				}
   885 			}
   886 			return;
   887 		} else if (strcmp(cmd, "info") == 0) {
   888 			if (argcount < 4)
   889 			{
   890 				g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
   891 				return;
   892 			}
   893 
   894 			const char *sId = command.Arg(3);
   895 			unsigned int id = atoi(sId);
   896 			if (id <= 0)
   897 			{
   898 				g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
   899 				return;
   900 			}
   901 
   902 			if (m_Libs.size() == 0)
   903 			{
   904 				g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
   905 				return;
   906 			}
   907 
   908 			if (id > m_Libs.size())
   909 			{
   910 				g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
   911 				return;
   912 			}
   913 
   914 			List<CExtension *>::iterator iter = m_Libs.begin();
   915 			CExtension *pExt = NULL;
   916 			while (iter != m_Libs.end())
   917 			{
   918 				if (--id == 0)
   919 				{
   920 					pExt = (*iter);
   921 					break;
   922 				}
   923 				iter++;
   924 			}
   925 			/* This should never happen */
   926 			if (!pExt)
   927 			{
   928 				g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
   929 				return;
   930 			}
   931 
   932 			if (!pExt->IsLoaded())
   933 			{
   934 				g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
   935 				g_RootMenu.ConsolePrint(" Loaded: No (%s)", pExt->m_Error.c_str());
   936 			} else {
   937 				char error[255];
   938 				if (!pExt->IsRunning(error, sizeof(error)))
   939 				{
   940 					g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
   941 					g_RootMenu.ConsolePrint(" Loaded: Yes");
   942 					g_RootMenu.ConsolePrint(" Running: No (%s)", error);
   943 				} else {
   944 					IExtensionInterface *pAPI = pExt->GetAPI();
   945 					g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
   946 					g_RootMenu.ConsolePrint(" Loaded: Yes (version %s)", pAPI->GetExtensionVerString());
   947 					g_RootMenu.ConsolePrint(" Name: %s (%s)", pAPI->GetExtensionName(), pAPI->GetExtensionDescription());
   948 					g_RootMenu.ConsolePrint(" Author: %s (%s)", pAPI->GetExtensionAuthor(), pAPI->GetExtensionURL());
   949 					g_RootMenu.ConsolePrint(" Binary info: API version %d (compiled %s)", pAPI->GetExtensionVersion(), pAPI->GetExtensionDateString());
   950 					g_RootMenu.ConsolePrint(" Metamod enabled: %s", pAPI->IsMetamodExtension() ? "yes" : "no");
   951 				}
   952 			}
   953 			return;
   954 		} else if (strcmp(cmd, "unload") == 0) {
   955 			if (argcount < 4)
   956 			{
   957 				g_RootMenu.ConsolePrint("[SM] Usage: sm unload <#> [code]");
   958 				return;
   959 			}
   960 
   961 			const char *arg = command.Arg(3);
   962 			unsigned int num = atoi(arg);
   963 			CExtension *pExt = FindByOrder(num);
   964 
   965 			if (!pExt)
   966 			{
   967 				g_RootMenu.ConsolePrint("[SM] Extension number %d was not found.", num);
   968 				return;
   969 			}
   970 
   971 			if (argcount > 4 && pExt->unload_code)
   972 			{
   973 				const char *unload = command.Arg(4);
   974 				if (pExt->unload_code == (unsigned)atoi(unload))
   975 				{
   976 					char filename[PLATFORM_MAX_PATH];
   977 					snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
   978 					UnloadExtension(pExt);
   979 					g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
   980 				}
   981 				else
   982 				{
   983 					g_RootMenu.ConsolePrint("[SM] Please try again, the correct unload code is \"%d\"", pExt->unload_code);
   984 				}
   985 				return;
   986 			}
   987 
   988 			if (!pExt->IsLoaded() 
   989 				|| (!pExt->m_ChildDeps.size() && !pExt->m_Plugins.size()))
   990 			{
   991 				char filename[PLATFORM_MAX_PATH];
   992 				snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
   993 				UnloadExtension(pExt);
   994 				g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
   995 				return;
   996 			}
   997 			else
   998 			{
   999 				List<IPlugin *> plugins;
  1000 				if (pExt->m_ChildDeps.size())
  1001 				{
  1002 					g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename());
  1003 					List<CExtension *>::iterator iter;
  1004 					CExtension *pOther;
  1005 					/* Get list of all extensions */
  1006 					for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
  1007 					{
  1008 						List<IfaceInfo>::iterator i_iter;
  1009 						pOther = (*iter);
  1010 						if (!pOther->IsLoaded() || pOther == pExt)
  1011 						{
  1012 							continue;
  1013 						}
  1014 						/* Get their dependencies */
  1015 						for (i_iter=pOther->m_Deps.begin();
  1016 							 i_iter!=pOther->m_Deps.end();
  1017 							 i_iter++)
  1018 						{
  1019 							/* Is this dependency to us? */
  1020 							if ((*i_iter).owner != pExt)
  1021 							{
  1022 								continue;
  1023 							}
  1024 							/* Will our dependent care? */
  1025 							if (!pExt->GetAPI()->QueryInterfaceDrop((*i_iter).iface))
  1026 							{
  1027 								g_RootMenu.ConsolePrint(" -> %s", pExt->GetFilename());
  1028 								/* Add to plugin unload list */
  1029 								List<IPlugin *>::iterator p_iter;
  1030 								for (p_iter=pOther->m_Plugins.begin();
  1031 									 p_iter!=pOther->m_Plugins.end();
  1032 									 p_iter++)
  1033 								{
  1034 									if (plugins.find((*p_iter)) == plugins.end())
  1035 									{
  1036 										plugins.push_back((*p_iter));
  1037 									}
  1038 								}
  1039 							}
  1040 						}
  1041 					}
  1042 				}
  1043 				if (pExt->m_Plugins.size())
  1044 				{
  1045 					g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename());
  1046 					List<IPlugin *>::iterator iter;
  1047 					IPlugin *pPlugin;
  1048 					for (iter = pExt->m_Plugins.begin(); iter != pExt->m_Plugins.end(); iter++)
  1049 					{
  1050 						pPlugin = (*iter);
  1051 						if (plugins.find(pPlugin) == plugins.end())
  1052 						{
  1053 							plugins.push_back(pPlugin);
  1054 						}
  1055 					}
  1056 					for (iter = plugins.begin(); iter != plugins.end(); iter++)
  1057 					{
  1058 						pPlugin = (*iter);
  1059 						g_RootMenu.ConsolePrint(" -> %s", pPlugin->GetFilename());
  1060 					}
  1061 				}
  1062 				srand(static_cast<int>(time(NULL)));
  1063 				pExt->unload_code = (rand() % 877) + 123;	//123 to 999
  1064 				g_RootMenu.ConsolePrint("[SM] To verify unloading %s, please use the following: ", pExt->GetFilename());
  1065 				g_RootMenu.ConsolePrint("[SM] sm exts unload %d %d", num, pExt->unload_code);
  1066 
  1067 				return;
  1068 			}
  1069 		}
  1070 	}
  1071 
  1072 	g_RootMenu.ConsolePrint("SourceMod Extensions Menu:");
  1073 	g_RootMenu.DrawGenericOption("info", "Extra extension information");
  1074 	g_RootMenu.DrawGenericOption("list", "List extensions");
  1075 	g_RootMenu.DrawGenericOption("unload", "Unload an extension");
  1076 }
  1077 
  1078 CExtension *CExtensionManager::GetExtensionFromIdent(IdentityToken_t *ptr)
  1079 {
  1080 	if (ptr->type == g_ExtType)
  1081 	{
  1082 		return (CExtension *)(ptr->ptr);
  1083 	}
  1084 
  1085 	return NULL;
  1086 }
  1087 
  1088 CExtensionManager::CExtensionManager()
  1089 {
  1090 }
  1091 
  1092 CExtensionManager::~CExtensionManager()
  1093 {
  1094 }