3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
16 #include "ExtensionSys.h"
17 #include "LibrarySys.h"
20 #include "sourcemm_api.h"
21 #include "PluginSys.h"
22 #include "sm_srvcmds.h"
23 #include "sm_stringutil.h"
25 CExtensionManager g_Extensions;
26 IdentityType_t g_ExtType;
28 CExtension::CExtension(const char *filename, char *error, size_t maxlength)
30 m_File.assign(filename);
35 m_FullyLoaded = false;
37 char path[PLATFORM_MAX_PATH];
38 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "extensions/%s", filename);
44 bool CExtension::Load(char *error, size_t maxlength)
46 m_pLib = g_LibSys.OpenLibrary(m_Path.c_str(), error, maxlength);
53 typedef IExtensionInterface *(*GETAPI)();
54 GETAPI pfnGetAPI = NULL;
56 if ((pfnGetAPI=(GETAPI)m_pLib->GetSymbolAddress("GetSMExtAPI")) == NULL)
58 m_pLib->CloseLibrary();
60 snprintf(error, maxlength, "Unable to find extension entry point");
65 if (!m_pAPI || m_pAPI->GetExtensionVersion() > SMINTERFACE_EXTENSIONAPI_VERSION)
67 m_pLib->CloseLibrary();
69 snprintf(error, maxlength, "Extension version is too new to load (%d, max is %d)", m_pAPI->GetExtensionVersion(), SMINTERFACE_EXTENSIONAPI_VERSION);
73 if (m_pAPI->IsMetamodExtension())
76 m_PlId = g_pMMPlugins->Load(m_Path.c_str(), g_PLID, already, error, maxlength);
79 m_pIdentToken = g_ShareSys.CreateIdentity(g_ExtType, this);
81 if (!m_pAPI->OnExtensionLoad(this, &g_ShareSys, error, maxlength, !g_SourceMod.IsMapLoading()))
83 if (m_pAPI->IsMetamodExtension())
88 g_pMMPlugins->Unload(m_PlId, true, dummy, sizeof(dummy));
93 m_pLib->CloseLibrary();
95 g_ShareSys.DestroyIdentity(m_pIdentToken);
99 /* Check if we're past load time */
100 if (!g_SourceMod.IsMapLoading())
102 m_pAPI->OnExtensionsAllLoaded();
109 CExtension::~CExtension()
113 m_pAPI->OnExtensionUnload();
116 g_pMMPlugins->Unload(m_PlId, true, NULL, 0);
122 g_ShareSys.DestroyIdentity(m_pIdentToken);
127 m_pLib->CloseLibrary();
131 void CExtension::MarkAllLoaded()
133 assert(m_FullyLoaded == false);
136 m_FullyLoaded = true;
137 m_pAPI->OnExtensionsAllLoaded();
141 void CExtension::AddPlugin(IPlugin *pPlugin)
143 /* Unfortunately we have to do this :( */
144 if (m_Plugins.find(pPlugin) != m_Plugins.end())
146 m_Plugins.push_back(pPlugin);
150 void CExtension::RemovePlugin(IPlugin *pPlugin)
152 m_Plugins.remove(pPlugin);
155 void CExtension::SetError(const char *error)
157 m_Error.assign(error);
160 IExtensionInterface *CExtension::GetAPI()
165 const char *CExtension::GetFilename()
167 return m_File.c_str();
170 IdentityToken_t *CExtension::GetIdentity()
172 return m_pIdentToken;
175 bool CExtension::IsLoaded()
177 return (m_pLib != NULL);
180 void CExtension::AddDependency(IfaceInfo *pInfo)
182 m_Deps.push_back(*pInfo);
185 ITERATOR *CExtension::FindFirstDependency(IExtension **pOwner, SMInterface **pInterface)
187 List<IfaceInfo>::iterator iter = m_Deps.begin();
189 if (iter == m_Deps.end())
196 *pOwner = (*iter).owner;
200 *pInterface = (*iter).iface;
203 List<IfaceInfo>::iterator *pIter = new List<IfaceInfo>::iterator(iter);
205 return (ITERATOR *)pIter;
208 bool CExtension::FindNextDependency(ITERATOR *iter, IExtension **pOwner, SMInterface **pInterface)
210 List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
211 List<IfaceInfo>::iterator _iter;
213 if (_iter == m_Deps.end())
222 *pOwner = (*_iter).owner;
226 *pInterface = (*_iter).iface;
231 if (_iter == m_Deps.end())
239 void CExtension::FreeDependencyIterator(ITERATOR *iter)
241 List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
246 void CExtension::AddInterface(SMInterface *pInterface)
248 m_Interfaces.push_back(pInterface);
251 bool CExtension::IsRunning(char *error, size_t maxlength)
257 snprintf(error, maxlength, "%s", m_Error.c_str());
262 return m_pAPI->QueryRunning(error, maxlength);
265 /*********************
266 * EXTENSION MANAGER *
267 *********************/
269 void CExtensionManager::OnSourceModAllInitialized()
271 g_ExtType = g_ShareSys.CreateIdentType("EXTENSION");
272 g_PluginSys.AddPluginsListener(this);
273 g_RootMenu.AddRootConsoleCommand("exts", "Manage extensions", this);
274 g_ShareSys.AddInterface(NULL, this);
277 void CExtensionManager::OnSourceModShutdown()
279 g_RootMenu.RemoveRootConsoleCommand("exts", this);
280 g_ShareSys.DestroyIdentType(g_ExtType);
283 void CExtensionManager::Shutdown()
285 List<CExtension *>::iterator iter;
287 while ((iter = m_Libs.begin()) != m_Libs.end())
289 UnloadExtension((*iter));
293 void CExtensionManager::TryAutoload()
295 char path[PLATFORM_MAX_PATH];
297 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "extensions");
299 IDirectory *pDir = g_LibSys.OpenDirectory(path);
307 while (pDir->MoreFiles())
309 if (pDir->IsEntryDirectory())
315 lfile = pDir->GetEntryName();
317 if (len <= 9) /* size of ".autoload" */
323 if (strcmp(&lfile[len - 9], ".autoload") != 0)
329 char file[PLATFORM_MAX_PATH];
330 len = UTIL_Format(file, sizeof(file), "%s", lfile);
331 strcpy(&file[len - 9], ".ext." PLATFORM_LIB_EXT);
333 LoadAutoExtension(file);
339 IExtension *CExtensionManager::LoadAutoExtension(const char *path)
341 if (!strstr(path, "." PLATFORM_LIB_EXT))
343 char newpath[PLATFORM_MAX_PATH];
344 snprintf(newpath, PLATFORM_MAX_PATH, "%s.%s", path, PLATFORM_LIB_EXT);
345 return LoadAutoExtension(newpath);
348 IExtension *pAlready;
349 if ((pAlready=FindExtensionByFile(path)) != NULL)
355 CExtension *p = new CExtension(path, error, sizeof(error));
357 /* We put us in the list beforehand so extensions that check for each other
358 * won't recursively load each other.
362 if (!p->Load(error, sizeof(error)) || !p->IsLoaded())
364 g_Logger.LogError("[SM] Unable to load extension \"%s\": %s", path, error);
371 IExtension *CExtensionManager::FindExtensionByFile(const char *file)
373 List<CExtension *>::iterator iter;
376 if (!strstr(file, "." PLATFORM_LIB_EXT))
378 char path[PLATFORM_MAX_PATH];
379 snprintf(path, PLATFORM_MAX_PATH, "%s.%s", file, PLATFORM_LIB_EXT);
380 return FindExtensionByFile(path);
383 /* Make sure the file direction is right */
384 char path[PLATFORM_MAX_PATH];
385 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
387 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
390 if (strcmp(pExt->GetFilename(), path) == 0)
399 IExtension *CExtensionManager::FindExtensionByName(const char *ext)
401 List<CExtension *>::iterator iter;
403 IExtensionInterface *pAPI;
406 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
409 if (!pExt->IsLoaded())
413 if ((pAPI = pExt->GetAPI()) == NULL)
417 name = pAPI->GetExtensionName();
422 if (strcmp(name, ext) == 0)
431 IExtension *CExtensionManager::LoadExtension(const char *file, ExtensionLifetime lifetime, char *error, size_t maxlength)
433 IExtension *pAlready;
434 if ((pAlready=FindExtensionByFile(file)) != NULL)
439 CExtension *pExt = new CExtension(file, error, maxlength);
441 /* :NOTE: lifetime is currently ignored */
443 if (!pExt->Load(error, maxlength) || !pExt->IsLoaded())
449 /* :TODO: do QueryRunning check if the map is loaded */
451 m_Libs.push_back(pExt);
456 void CExtensionManager::BindDependency(IExtension *pOwner, IfaceInfo *pInfo)
458 CExtension *pExt = (CExtension *)pOwner;
460 pExt->AddDependency(pInfo);
463 void CExtensionManager::AddInterface(IExtension *pOwner, SMInterface *pInterface)
465 CExtension *pExt = (CExtension *)pOwner;
467 pExt->AddInterface(pInterface);
470 void CExtensionManager::BindChildPlugin(IExtension *pParent, IPlugin *pPlugin)
472 CExtension *pExt = (CExtension *)pParent;
474 pExt->AddPlugin(pPlugin);
477 void CExtensionManager::OnPluginDestroyed(IPlugin *plugin)
479 List<CExtension *>::iterator iter;
481 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
483 (*iter)->RemovePlugin(plugin);
487 CExtension *CExtensionManager::FindByOrder(unsigned int num)
489 if (num < 1 || num > m_Libs.size())
494 List<CExtension *>::iterator iter = m_Libs.begin();
496 while (iter != m_Libs.end())
508 void CExtensionManager::BindAllNativesToPlugin(IPlugin *pPlugin)
510 List<CExtension *>::iterator iter;
512 IPluginContext *pContext = pPlugin->GetBaseContext();
513 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
516 if (!pExt->IsLoaded())
520 if (!pExt->m_Natives.size())
525 List<const sp_nativeinfo_t *>::iterator n_iter;
526 const sp_nativeinfo_t *natives;
527 for (n_iter = pExt->m_Natives.begin();
528 n_iter != pExt->m_Natives.end();
533 while (natives[i].func != NULL && natives[i].name != NULL)
535 if (pContext->BindNative(&natives[i++]) == SP_ERROR_NONE)
541 if (set && (pExt->m_Plugins.find(pPlugin) == pExt->m_Plugins.end()))
543 /* For now, mark this plugin as a requirement. Later we'll introduce native filtering. */
544 pExt->m_Plugins.push_back(pPlugin);
549 bool CExtensionManager::UnloadExtension(IExtension *_pExt)
556 CExtension *pExt = (CExtension *)_pExt;
558 if (m_Libs.find(pExt) == m_Libs.end())
563 /* First remove us from internal lists */
564 g_ShareSys.RemoveInterfaces(_pExt);
567 List<CExtension *> UnloadQueue;
569 /* Handle dependencies */
570 if (pExt->IsLoaded())
572 /* Unload any dependent plugins */
573 List<IPlugin *>::iterator p_iter = pExt->m_Plugins.begin();
574 while (p_iter != pExt->m_Plugins.end())
576 /* We have to manually unlink ourselves here, since we're no longer being managed */
577 g_PluginSys.UnloadPlugin((*p_iter));
578 p_iter = pExt->m_Plugins.erase(p_iter);
581 /* Notify and/or unload all dependencies */
582 List<CExtension *>::iterator c_iter;
584 IExtensionInterface *pAPI;
585 for (c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
588 if ((pAPI=pDep->GetAPI()) == NULL)
596 /* Now, get its dependency list */
597 bool dropped = false;
598 List<IfaceInfo>::iterator i_iter = pDep->m_Deps.begin();
599 while (i_iter != pDep->m_Deps.end())
601 if ((*i_iter).owner == _pExt)
603 if (!dropped && !pAPI->QueryInterfaceDrop((*i_iter).iface))
607 pAPI->NotifyInterfaceDrop((*i_iter).iface);
608 i_iter = pDep->m_Deps.erase(i_iter);
618 List<CExtension *>::iterator iter;
619 for (iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
621 /* NOTE: This is safe because the unload function backs out of anything not present */
622 UnloadExtension((*iter));
628 void CExtensionManager::AddNatives(IExtension *pOwner, const sp_nativeinfo_t *natives)
630 CExtension *pExt = (CExtension *)pOwner;
632 pExt->m_Natives.push_back(natives);
635 void CExtensionManager::MarkAllLoaded()
637 List<CExtension *>::iterator iter;
640 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
643 if (!pExt->IsLoaded())
647 if (pExt->m_FullyLoaded)
651 pExt->MarkAllLoaded();
655 void CExtensionManager::AddDependency(IExtension *pSource, const char *file, bool required, bool autoload)
657 /* This function doesn't really need to do anything now. We make sure the
658 * other extension is loaded, but handling of dependencies is really done
659 * by the interface fetcher.
661 if (required || autoload)
663 LoadAutoExtension(file);
667 void CExtensionManager::OnRootConsoleCommand(const char *cmd, unsigned int argcount)
671 const char *cmd = g_RootMenu.GetArgument(2);
672 if (strcmp(cmd, "list") == 0)
674 List<CExtension *>::iterator iter;
676 unsigned int num = 1;
677 switch (m_Libs.size())
681 g_RootMenu.ConsolePrint("[SM] Displaying 1 extension:");
686 g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
691 g_RootMenu.ConsolePrint("[SM] Displaying %d extensions:", m_Libs.size());
695 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++,num++)
698 if (pExt->IsLoaded())
701 if (!pExt->IsRunning(error, sizeof(error)))
703 g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), error);
705 IExtensionInterface *pAPI = pExt->GetAPI();
706 const char *name = pAPI->GetExtensionName();
707 const char *version = pAPI->GetExtensionVerString();
708 const char *descr = pAPI->GetExtensionDescription();
709 g_RootMenu.ConsolePrint("[%02d] %s (%s): %s", num, name, version, descr);
712 g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), pExt->m_Error.c_str());
716 } else if (strcmp(cmd, "info") == 0) {
719 g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
723 const char *sId = g_RootMenu.GetArgument(3);
724 unsigned int id = atoi(sId);
727 g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
731 if (m_Libs.size() == 0)
733 g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
737 if (id > m_Libs.size())
739 g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
743 List<CExtension *>::iterator iter = m_Libs.begin();
744 CExtension *pExt = NULL;
745 while (iter != m_Libs.end())
754 /* This should never happen */
757 g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
761 if (!pExt->IsLoaded())
763 g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
764 g_RootMenu.ConsolePrint(" Loaded: No (%s)", pExt->m_Error.c_str());
767 if (!pExt->IsRunning(error, sizeof(error)))
769 g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
770 g_RootMenu.ConsolePrint(" Loaded: Yes");
771 g_RootMenu.ConsolePrint(" Running: No (%s)", error);
773 IExtensionInterface *pAPI = pExt->GetAPI();
774 g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
775 g_RootMenu.ConsolePrint(" Loaded: Yes (version %s)", pAPI->GetExtensionVerString());
776 g_RootMenu.ConsolePrint(" Name: %s (%s)", pAPI->GetExtensionName(), pAPI->GetExtensionDescription());
777 g_RootMenu.ConsolePrint(" Author: %s (%s)", pAPI->GetExtensionAuthor(), pAPI->GetExtensionURL());
778 g_RootMenu.ConsolePrint(" Binary info: API version %d (compiled %s)", pAPI->GetExtensionVersion(), pAPI->GetExtensionDateString());
779 g_RootMenu.ConsolePrint(" Metamod enabled: %s", pAPI->IsMetamodExtension() ? "yes" : "no");
783 } else if (strcmp(cmd, "unload") == 0) {
786 g_RootMenu.ConsolePrint("[SM] Usage: sm unload <#> [code]");
790 const char *arg = g_RootMenu.GetArgument(3);
791 unsigned int num = atoi(arg);
792 CExtension *pExt = FindByOrder(num);
796 g_RootMenu.ConsolePrint("[SM] Extension number %d was not found.", num);
800 if (argcount > 4 && pExt->unload_code)
802 const char *unload = g_RootMenu.GetArgument(4);
803 if (pExt->unload_code == (unsigned)atoi(unload))
805 char filename[PLATFORM_MAX_PATH];
806 snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
807 UnloadExtension(pExt);
808 g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
810 g_RootMenu.ConsolePrint("[SM] Please try again, the correct unload code is \"%d\"", pExt->unload_code);
815 if (!pExt->IsLoaded()
816 || (!pExt->m_Deps.size() && !pExt->m_Plugins.size()))
818 char filename[PLATFORM_MAX_PATH];
819 snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
820 UnloadExtension(pExt);
821 g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
824 List<IPlugin *> plugins;
825 if (pExt->m_Deps.size())
827 g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename());
828 List<CExtension *>::iterator iter;
830 /* Get list of all extensions */
831 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
833 List<IfaceInfo>::iterator i_iter;
835 if (!pOther->IsLoaded() || pOther == pExt)
839 /* Get their dependencies */
840 for (i_iter=pOther->m_Deps.begin();
841 i_iter!=pOther->m_Deps.end();
844 /* Is this dependency to us? */
845 if ((*i_iter).owner != pExt)
849 /* Will our dependent care? */
850 if (!pExt->GetAPI()->QueryInterfaceDrop((*i_iter).iface))
852 g_RootMenu.ConsolePrint(" -> %s", pExt->GetFilename());
853 /* Add to plugin unload list */
854 List<IPlugin *>::iterator p_iter;
855 for (p_iter=pOther->m_Plugins.begin();
856 p_iter!=pOther->m_Plugins.end();
859 if (plugins.find((*p_iter)) == plugins.end())
861 plugins.push_back((*p_iter));
868 if (pExt->m_Plugins.size())
870 g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename());
871 List<IPlugin *>::iterator iter;
873 for (iter = pExt->m_Plugins.begin(); iter != pExt->m_Plugins.end(); iter++)
876 if (plugins.find(pPlugin) == plugins.end())
878 plugins.push_back(pPlugin);
881 for (iter = plugins.begin(); iter != plugins.end(); iter++)
884 g_RootMenu.ConsolePrint(" -> %s", pPlugin->GetFilename());
887 srand(static_cast<int>(time(NULL)));
888 pExt->unload_code = (rand() % 877) + 123; //123 to 999
889 g_RootMenu.ConsolePrint("[SM] To verify unloading %s, please use the following: ", pExt->GetFilename());
890 g_RootMenu.ConsolePrint("[SM] sm exts unload %d %d", num, pExt->unload_code);
897 g_RootMenu.ConsolePrint("SourceMod Extensions Menu:");
898 g_RootMenu.DrawGenericOption("info", "Extra extension information");
899 g_RootMenu.DrawGenericOption("list", "List extensions");
900 g_RootMenu.DrawGenericOption("unload", "Unload an extension");
903 CExtension *CExtensionManager::GetExtensionFromIdent(IdentityToken_t *ptr)
905 if (ptr->type == g_ExtType)
907 return (CExtension *)(ptr->ptr);