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