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 "sm_srvcmds.h"
22 #include "sm_stringutil.h"
24 CExtensionManager g_Extensions;
25 IdentityType_t g_ExtType;
27 CExtension::CExtension(const char *filename, char *error, size_t maxlength)
29 m_File.assign(filename);
34 m_FullyLoaded = false;
36 char path[PLATFORM_MAX_PATH];
37 g_SourceMod.BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "extensions/%s", filename);
43 bool CExtension::Load(char *error, size_t maxlength)
45 m_pLib = g_LibSys.OpenLibrary(m_Path.c_str(), error, maxlength);
52 typedef IExtensionInterface *(*GETAPI)();
53 GETAPI pfnGetAPI = NULL;
55 if ((pfnGetAPI=(GETAPI)m_pLib->GetSymbolAddress("GetSMExtAPI")) == NULL)
57 m_pLib->CloseLibrary();
59 snprintf(error, maxlength, "Unable to find extension entry point");
64 if (!m_pAPI || m_pAPI->GetExtensionVersion() > SMINTERFACE_EXTENSIONAPI_VERSION)
66 m_pLib->CloseLibrary();
68 snprintf(error, maxlength, "Extension version is too new to load (%d, max is %d)", m_pAPI->GetExtensionVersion(), SMINTERFACE_EXTENSIONAPI_VERSION);
72 if (m_pAPI->IsMetamodExtension())
75 m_PlId = g_pMMPlugins->Load(m_Path.c_str(), g_PLID, already, error, maxlength);
78 m_pIdentToken = g_ShareSys.CreateIdentity(g_ExtType, this);
80 if (!m_pAPI->OnExtensionLoad(this, &g_ShareSys, error, maxlength, !g_SourceMod.IsMapLoading()))
82 if (m_pAPI->IsMetamodExtension())
87 g_pMMPlugins->Unload(m_PlId, true, dummy, sizeof(dummy));
92 m_pLib->CloseLibrary();
94 g_ShareSys.DestroyIdentity(m_pIdentToken);
98 /* Check if we're past load time */
99 if (!g_SourceMod.IsMapLoading())
101 m_pAPI->OnExtensionsAllLoaded();
108 CExtension::~CExtension()
112 m_pAPI->OnExtensionUnload();
115 g_pMMPlugins->Unload(m_PlId, true, NULL, 0);
121 g_ShareSys.DestroyIdentity(m_pIdentToken);
126 m_pLib->CloseLibrary();
129 List<WeakNative *>::iterator iter;
130 for (iter=m_WeakNatives.begin(); iter!=m_WeakNatives.end(); iter++)
134 m_WeakNatives.clear();
137 void CExtension::MarkAllLoaded()
139 assert(m_FullyLoaded == false);
142 m_FullyLoaded = true;
143 m_pAPI->OnExtensionsAllLoaded();
147 void CExtension::AddPlugin(IPlugin *pPlugin)
149 /* Unfortunately we have to do this :( */
150 if (m_Plugins.find(pPlugin) != m_Plugins.end())
152 m_Plugins.push_back(pPlugin);
156 void CExtension::RemovePlugin(IPlugin *pPlugin)
158 m_Plugins.remove(pPlugin);
161 void CExtension::SetError(const char *error)
163 m_Error.assign(error);
166 IExtensionInterface *CExtension::GetAPI()
171 const char *CExtension::GetFilename()
173 return m_File.c_str();
176 IdentityToken_t *CExtension::GetIdentity()
178 return m_pIdentToken;
181 bool CExtension::IsLoaded()
183 return (m_pLib != NULL);
186 void CExtension::AddDependency(IfaceInfo *pInfo)
188 m_Deps.push_back(*pInfo);
191 ITERATOR *CExtension::FindFirstDependency(IExtension **pOwner, SMInterface **pInterface)
193 List<IfaceInfo>::iterator iter = m_Deps.begin();
195 if (iter == m_Deps.end())
202 *pOwner = (*iter).owner;
206 *pInterface = (*iter).iface;
209 List<IfaceInfo>::iterator *pIter = new List<IfaceInfo>::iterator(iter);
211 return (ITERATOR *)pIter;
214 bool CExtension::FindNextDependency(ITERATOR *iter, IExtension **pOwner, SMInterface **pInterface)
216 List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
217 List<IfaceInfo>::iterator _iter;
219 if (_iter == m_Deps.end())
228 *pOwner = (*_iter).owner;
232 *pInterface = (*_iter).iface;
237 if (_iter == m_Deps.end())
245 void CExtension::FreeDependencyIterator(ITERATOR *iter)
247 List<IfaceInfo>::iterator *pIter = (List<IfaceInfo>::iterator *)iter;
252 void CExtension::AddInterface(SMInterface *pInterface)
254 m_Interfaces.push_back(pInterface);
257 bool CExtension::IsRunning(char *error, size_t maxlength)
263 snprintf(error, maxlength, "%s", m_Error.c_str());
268 return m_pAPI->QueryRunning(error, maxlength);
271 /*********************
272 * EXTENSION MANAGER *
273 *********************/
275 void CExtensionManager::OnSourceModAllInitialized()
277 g_ExtType = g_ShareSys.CreateIdentType("EXTENSION");
278 g_PluginSys.AddPluginsListener(this);
279 g_RootMenu.AddRootConsoleCommand("exts", "Manage extensions", this);
280 g_ShareSys.AddInterface(NULL, this);
283 void CExtensionManager::OnSourceModShutdown()
285 g_RootMenu.RemoveRootConsoleCommand("exts", this);
286 g_ShareSys.DestroyIdentType(g_ExtType);
289 void CExtensionManager::Shutdown()
291 List<CExtension *>::iterator iter;
293 while ((iter = m_Libs.begin()) != m_Libs.end())
295 UnloadExtension((*iter));
299 void CExtensionManager::TryAutoload()
301 char path[PLATFORM_MAX_PATH];
303 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "extensions");
305 IDirectory *pDir = g_LibSys.OpenDirectory(path);
313 while (pDir->MoreFiles())
315 if (pDir->IsEntryDirectory())
321 lfile = pDir->GetEntryName();
323 if (len <= 9) /* size of ".autoload" */
329 if (strcmp(&lfile[len - 9], ".autoload") != 0)
335 char file[PLATFORM_MAX_PATH];
336 len = UTIL_Format(file, sizeof(file), "%s", lfile);
337 strcpy(&file[len - 9], ".ext." PLATFORM_LIB_EXT);
339 LoadAutoExtension(file);
345 IExtension *CExtensionManager::LoadAutoExtension(const char *path)
347 if (!strstr(path, "." PLATFORM_LIB_EXT))
349 char newpath[PLATFORM_MAX_PATH];
350 snprintf(newpath, PLATFORM_MAX_PATH, "%s.%s", path, PLATFORM_LIB_EXT);
351 return LoadAutoExtension(newpath);
354 IExtension *pAlready;
355 if ((pAlready=FindExtensionByFile(path)) != NULL)
361 CExtension *p = new CExtension(path, error, sizeof(error));
363 /* We put us in the list beforehand so extensions that check for each other
364 * won't recursively load each other.
368 if (!p->Load(error, sizeof(error)) || !p->IsLoaded())
370 g_Logger.LogError("[SM] Unable to load extension \"%s\": %s", path, error);
377 IExtension *CExtensionManager::FindExtensionByFile(const char *file)
379 List<CExtension *>::iterator iter;
382 if (!strstr(file, "." PLATFORM_LIB_EXT))
384 char path[PLATFORM_MAX_PATH];
385 snprintf(path, PLATFORM_MAX_PATH, "%s.%s", file, PLATFORM_LIB_EXT);
386 return FindExtensionByFile(path);
389 /* Make sure the file direction is right */
390 char path[PLATFORM_MAX_PATH];
391 g_LibSys.PathFormat(path, PLATFORM_MAX_PATH, "%s", file);
393 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
396 if (strcmp(pExt->GetFilename(), path) == 0)
405 IExtension *CExtensionManager::FindExtensionByName(const char *ext)
407 List<CExtension *>::iterator iter;
409 IExtensionInterface *pAPI;
412 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
415 if (!pExt->IsLoaded())
419 if ((pAPI = pExt->GetAPI()) == NULL)
423 name = pAPI->GetExtensionName();
428 if (strcmp(name, ext) == 0)
437 IExtension *CExtensionManager::LoadExtension(const char *file, ExtensionLifetime lifetime, char *error, size_t maxlength)
439 IExtension *pAlready;
440 if ((pAlready=FindExtensionByFile(file)) != NULL)
445 CExtension *pExt = new CExtension(file, error, maxlength);
447 /* :NOTE: lifetime is currently ignored */
449 if (!pExt->Load(error, maxlength) || !pExt->IsLoaded())
455 /* :TODO: do QueryRunning check if the map is loaded */
457 m_Libs.push_back(pExt);
462 void CExtensionManager::BindDependency(IExtension *pOwner, IfaceInfo *pInfo)
464 CExtension *pExt = (CExtension *)pOwner;
466 pExt->AddDependency(pInfo);
469 void CExtensionManager::AddInterface(IExtension *pOwner, SMInterface *pInterface)
471 CExtension *pExt = (CExtension *)pOwner;
473 pExt->AddInterface(pInterface);
476 void CExtensionManager::BindChildPlugin(IExtension *pParent, IPlugin *pPlugin)
478 CExtension *pExt = (CExtension *)pParent;
480 pExt->AddPlugin(pPlugin);
483 void CExtensionManager::OnPluginDestroyed(IPlugin *plugin)
485 List<CExtension *>::iterator iter;
487 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
489 (*iter)->RemovePlugin(plugin);
493 CExtension *CExtensionManager::FindByOrder(unsigned int num)
495 if (num < 1 || num > m_Libs.size())
500 List<CExtension *>::iterator iter = m_Libs.begin();
502 while (iter != m_Libs.end())
514 void CExtensionManager::BindAllNativesToPlugin(IPlugin *pPlugin)
516 List<CExtension *>::iterator iter;
518 IPluginContext *pContext = pPlugin->GetBaseContext();
519 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
522 if (!pExt->IsLoaded())
526 if (!pExt->m_Natives.size())
531 List<const sp_nativeinfo_t *>::iterator n_iter;
532 const sp_nativeinfo_t *natives;
533 for (n_iter = pExt->m_Natives.begin();
534 n_iter != pExt->m_Natives.end();
540 while (natives[i].func != NULL && natives[i].name != NULL)
542 if (pContext->BindNative(&natives[i]) == SP_ERROR_NONE)
544 pContext->FindNativeByName(natives[i].name, &idx);
545 if (!(pContext->GetContext()->natives[idx].flags & SP_NTVFLAG_OPTIONAL))
549 WeakNative *wkn = new WeakNative((CPlugin *)pPlugin, idx);
550 pExt->m_WeakNatives.push_back(wkn);
556 if (set && (pExt->m_Plugins.find(pPlugin) == pExt->m_Plugins.end()))
558 /* For now, mark this plugin as a requirement. Later we'll introduce native filtering. */
559 pExt->m_Plugins.push_back(pPlugin);
564 bool CExtensionManager::UnloadExtension(IExtension *_pExt)
571 CExtension *pExt = (CExtension *)_pExt;
573 if (m_Libs.find(pExt) == m_Libs.end())
578 /* First remove us from internal lists */
579 g_ShareSys.RemoveInterfaces(_pExt);
582 List<CExtension *> UnloadQueue;
584 /* Handle dependencies */
585 if (pExt->IsLoaded())
587 /* Unload any dependent plugins */
588 List<IPlugin *>::iterator p_iter = pExt->m_Plugins.begin();
589 while (p_iter != pExt->m_Plugins.end())
591 /* We have to manually unlink ourselves here, since we're no longer being managed */
592 g_PluginSys.UnloadPlugin((*p_iter));
593 p_iter = pExt->m_Plugins.erase(p_iter);
596 /* Unbound weak natives */
598 List<WeakNative *>::iterator wkn_iter;
599 for (wkn_iter=pExt->m_WeakNatives.begin(); wkn_iter!=pExt->m_WeakNatives.end(); wkn_iter++)
602 sp_context_t *ctx = wkn->pl->GetContext();
603 ctx->natives[wkn->idx].status = SP_NATIVE_UNBOUND;
606 /* Notify and/or unload all dependencies */
607 List<CExtension *>::iterator c_iter;
609 IExtensionInterface *pAPI;
610 for (c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
613 if ((pAPI=pDep->GetAPI()) == NULL)
621 /* Now, get its dependency list */
622 bool dropped = false;
623 List<IfaceInfo>::iterator i_iter = pDep->m_Deps.begin();
624 while (i_iter != pDep->m_Deps.end())
626 if ((*i_iter).owner == _pExt)
628 if (!dropped && !pAPI->QueryInterfaceDrop((*i_iter).iface))
632 pAPI->NotifyInterfaceDrop((*i_iter).iface);
633 i_iter = pDep->m_Deps.erase(i_iter);
643 List<CExtension *>::iterator iter;
644 for (iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
646 /* NOTE: This is safe because the unload function backs out of anything not present */
647 UnloadExtension((*iter));
653 void CExtensionManager::AddNatives(IExtension *pOwner, const sp_nativeinfo_t *natives)
655 CExtension *pExt = (CExtension *)pOwner;
657 pExt->m_Natives.push_back(natives);
660 void CExtensionManager::MarkAllLoaded()
662 List<CExtension *>::iterator iter;
665 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
668 if (!pExt->IsLoaded())
672 if (pExt->m_FullyLoaded)
676 pExt->MarkAllLoaded();
680 void CExtensionManager::AddDependency(IExtension *pSource, const char *file, bool required, bool autoload)
682 /* This function doesn't really need to do anything now. We make sure the
683 * other extension is loaded, but handling of dependencies is really done
684 * by the interface fetcher.
686 if (required || autoload)
688 LoadAutoExtension(file);
692 void CExtensionManager::OnRootConsoleCommand(const char *cmd, unsigned int argcount)
696 const char *cmd = g_RootMenu.GetArgument(2);
697 if (strcmp(cmd, "list") == 0)
699 List<CExtension *>::iterator iter;
701 unsigned int num = 1;
702 switch (m_Libs.size())
706 g_RootMenu.ConsolePrint("[SM] Displaying 1 extension:");
711 g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
716 g_RootMenu.ConsolePrint("[SM] Displaying %d extensions:", m_Libs.size());
720 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++,num++)
723 if (pExt->IsLoaded())
726 if (!pExt->IsRunning(error, sizeof(error)))
728 g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), error);
730 IExtensionInterface *pAPI = pExt->GetAPI();
731 const char *name = pAPI->GetExtensionName();
732 const char *version = pAPI->GetExtensionVerString();
733 const char *descr = pAPI->GetExtensionDescription();
734 g_RootMenu.ConsolePrint("[%02d] %s (%s): %s", num, name, version, descr);
737 g_RootMenu.ConsolePrint("[%02d] <FAILED> file \"%s\": %s", num, pExt->GetFilename(), pExt->m_Error.c_str());
741 } else if (strcmp(cmd, "info") == 0) {
744 g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
748 const char *sId = g_RootMenu.GetArgument(3);
749 unsigned int id = atoi(sId);
752 g_RootMenu.ConsolePrint("[SM] Usage: sm info <#>");
756 if (m_Libs.size() == 0)
758 g_RootMenu.ConsolePrint("[SM] No extensions are loaded.");
762 if (id > m_Libs.size())
764 g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
768 List<CExtension *>::iterator iter = m_Libs.begin();
769 CExtension *pExt = NULL;
770 while (iter != m_Libs.end())
779 /* This should never happen */
782 g_RootMenu.ConsolePrint("[SM] No extension was found with id %d.", id);
786 if (!pExt->IsLoaded())
788 g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
789 g_RootMenu.ConsolePrint(" Loaded: No (%s)", pExt->m_Error.c_str());
792 if (!pExt->IsRunning(error, sizeof(error)))
794 g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
795 g_RootMenu.ConsolePrint(" Loaded: Yes");
796 g_RootMenu.ConsolePrint(" Running: No (%s)", error);
798 IExtensionInterface *pAPI = pExt->GetAPI();
799 g_RootMenu.ConsolePrint(" File: %s", pExt->GetFilename());
800 g_RootMenu.ConsolePrint(" Loaded: Yes (version %s)", pAPI->GetExtensionVerString());
801 g_RootMenu.ConsolePrint(" Name: %s (%s)", pAPI->GetExtensionName(), pAPI->GetExtensionDescription());
802 g_RootMenu.ConsolePrint(" Author: %s (%s)", pAPI->GetExtensionAuthor(), pAPI->GetExtensionURL());
803 g_RootMenu.ConsolePrint(" Binary info: API version %d (compiled %s)", pAPI->GetExtensionVersion(), pAPI->GetExtensionDateString());
804 g_RootMenu.ConsolePrint(" Metamod enabled: %s", pAPI->IsMetamodExtension() ? "yes" : "no");
808 } else if (strcmp(cmd, "unload") == 0) {
811 g_RootMenu.ConsolePrint("[SM] Usage: sm unload <#> [code]");
815 const char *arg = g_RootMenu.GetArgument(3);
816 unsigned int num = atoi(arg);
817 CExtension *pExt = FindByOrder(num);
821 g_RootMenu.ConsolePrint("[SM] Extension number %d was not found.", num);
825 if (argcount > 4 && pExt->unload_code)
827 const char *unload = g_RootMenu.GetArgument(4);
828 if (pExt->unload_code == (unsigned)atoi(unload))
830 char filename[PLATFORM_MAX_PATH];
831 snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
832 UnloadExtension(pExt);
833 g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
835 g_RootMenu.ConsolePrint("[SM] Please try again, the correct unload code is \"%d\"", pExt->unload_code);
840 if (!pExt->IsLoaded()
841 || (!pExt->m_Deps.size() && !pExt->m_Plugins.size()))
843 char filename[PLATFORM_MAX_PATH];
844 snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename());
845 UnloadExtension(pExt);
846 g_RootMenu.ConsolePrint("[SM] Extension %s is now unloaded.", filename);
849 List<IPlugin *> plugins;
850 if (pExt->m_Deps.size())
852 g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename());
853 List<CExtension *>::iterator iter;
855 /* Get list of all extensions */
856 for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
858 List<IfaceInfo>::iterator i_iter;
860 if (!pOther->IsLoaded() || pOther == pExt)
864 /* Get their dependencies */
865 for (i_iter=pOther->m_Deps.begin();
866 i_iter!=pOther->m_Deps.end();
869 /* Is this dependency to us? */
870 if ((*i_iter).owner != pExt)
874 /* Will our dependent care? */
875 if (!pExt->GetAPI()->QueryInterfaceDrop((*i_iter).iface))
877 g_RootMenu.ConsolePrint(" -> %s", pExt->GetFilename());
878 /* Add to plugin unload list */
879 List<IPlugin *>::iterator p_iter;
880 for (p_iter=pOther->m_Plugins.begin();
881 p_iter!=pOther->m_Plugins.end();
884 if (plugins.find((*p_iter)) == plugins.end())
886 plugins.push_back((*p_iter));
893 if (pExt->m_Plugins.size())
895 g_RootMenu.ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename());
896 List<IPlugin *>::iterator iter;
898 for (iter = pExt->m_Plugins.begin(); iter != pExt->m_Plugins.end(); iter++)
901 if (plugins.find(pPlugin) == plugins.end())
903 plugins.push_back(pPlugin);
906 for (iter = plugins.begin(); iter != plugins.end(); iter++)
909 g_RootMenu.ConsolePrint(" -> %s", pPlugin->GetFilename());
912 srand(static_cast<int>(time(NULL)));
913 pExt->unload_code = (rand() % 877) + 123; //123 to 999
914 g_RootMenu.ConsolePrint("[SM] To verify unloading %s, please use the following: ", pExt->GetFilename());
915 g_RootMenu.ConsolePrint("[SM] sm exts unload %d %d", num, pExt->unload_code);
922 g_RootMenu.ConsolePrint("SourceMod Extensions Menu:");
923 g_RootMenu.DrawGenericOption("info", "Extra extension information");
924 g_RootMenu.DrawGenericOption("list", "List extensions");
925 g_RootMenu.DrawGenericOption("unload", "Unload an extension");
928 CExtension *CExtensionManager::GetExtensionFromIdent(IdentityToken_t *ptr)
930 if (ptr->type == g_ExtType)
932 return (CExtension *)(ptr->ptr);