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