3 #include "LibrarySys.h"
5 #include "sourcemm_api.h"
7 #include "CTextParsers.h"
9 CPluginManager g_PluginSys;
10 HandleType_t g_PluginType = 0;
12 CPlugin::CPlugin(const char *file)
14 static int MySerial = 0;
16 m_type = PluginType_Private;
17 m_status = Plugin_Uncompiled;
18 m_serial = ++MySerial;
23 m_errormsg[256] = '\0';
24 snprintf(m_filename, sizeof(m_filename), "%s", file);
25 /* :TODO: ShareSys token */
26 m_handle = g_HandleSys.CreateHandle(g_PluginType, this, DEFAULT_IDENTITY, 1);
33 g_pSourcePawn->FreeBaseContext(m_ctx.base);
38 m_ctx.vm->FreeContext(m_ctx.ctx);
43 m_ctx.vm->AbortCompilation(m_ctx.co);
49 for (uint32_t i=0; i<m_plugin->info.publics_num; i++)
51 g_PluginSys.ReleaseFunctionToPool(m_pub_funcs[i]);
53 delete [] m_pub_funcs;
59 g_pSourcePawn->FreeFromMemory(m_plugin);
65 for (unsigned int i=0; i<m_funcsnum; i++)
67 g_PluginSys.ReleaseFunctionToPool(m_priv_funcs[i]);
69 delete [] m_priv_funcs;
74 CPlugin *CPlugin::CreatePlugin(const char *file, char *error, size_t maxlength)
76 char fullpath[PLATFORM_MAX_PATH+1];
77 g_LibSys.PathFormat(fullpath, sizeof(fullpath), "%s/plugins/%s", g_SourceMod.GetSMBaseDir(), file);
78 FILE *fp = fopen(fullpath, "rb");
84 snprintf(error, maxlength, "Unable to open file");
87 CPlugin *pPlugin = new CPlugin(file);
88 snprintf(pPlugin->m_errormsg, sizeof(pPlugin->m_errormsg), "Unable to open file");
89 pPlugin->m_status = Plugin_BadLoad;
95 sp_plugin_t *pl = g_pSourcePawn->LoadFromFilePointer(fp, &err);
101 snprintf(error, maxlength, "Error %d while parsing plugin", err);
104 CPlugin *pPlugin = new CPlugin(file);
105 snprintf(pPlugin->m_errormsg, sizeof(pPlugin->m_errormsg), "Error %d while parsing plugin", err);
106 pPlugin->m_status = Plugin_BadLoad;
113 CPlugin *pPlugin = new CPlugin(file);
114 pPlugin->m_plugin = pl;
118 ICompilation *CPlugin::StartMyCompile(IVirtualMachine *vm)
125 /* :NOTICE: We will eventually need to change these natives
126 * for swapping in new contexts
128 if (m_ctx.co || m_ctx.ctx)
133 m_status = Plugin_Uncompiled;
136 m_ctx.co = vm->StartCompilation(m_plugin);
141 void CPlugin::CancelMyCompile()
148 m_ctx.vm->AbortCompilation(m_ctx.co);
153 bool CPlugin::FinishMyCompile(char *error, size_t maxlength)
161 m_ctx.ctx = m_ctx.vm->CompileToContext(m_ctx.co, &err);
164 memset(&m_ctx, 0, sizeof(m_ctx));
167 SetErrorState(Plugin_Error, "Failed to compile (error %d)", err);
169 snprintf(error, maxlength, "Failed to compile (error %d)", err);
174 m_ctx.base = g_pSourcePawn->CreateBaseContext(m_ctx.ctx);
175 m_ctx.ctx->user[SM_CONTEXTVAR_MYSELF] = (void *)this;
177 m_funcsnum = m_ctx.vm->FunctionCount(m_ctx.ctx);
180 * Note: Since the m_plugin member will never change,
181 * it is safe to assume the function count will never change
183 if (m_funcsnum && m_priv_funcs == NULL)
185 m_priv_funcs = new CFunction *[m_funcsnum];
186 memset(m_priv_funcs, 0, sizeof(CFunction *) * m_funcsnum);
191 if (m_plugin->info.publics_num && m_pub_funcs == NULL)
193 m_pub_funcs = new CFunction *[m_plugin->info.publics_num];
194 memset(m_pub_funcs, 0, sizeof(CFunction *) * m_plugin->info.publics_num);
199 m_status = Plugin_Created;
207 void CPlugin::SetErrorState(PluginStatus status, const char *error_fmt, ...)
212 va_start(ap, error_fmt);
213 vsnprintf(m_errormsg, sizeof(m_errormsg), error_fmt, ap);
217 IPluginFunction *CPlugin::GetFunctionById(funcid_t func_id)
219 CFunction *pFunc = NULL;
220 funcid_t save = func_id;
225 if (func_id >= m_plugin->info.publics_num)
229 pFunc = m_pub_funcs[func_id];
232 pFunc = g_PluginSys.GetFunctionFromPool(save, this);
233 m_pub_funcs[func_id] = pFunc;
238 if (!g_pVM->FunctionLookup(m_ctx.ctx, func_id, &index))
242 pFunc = m_priv_funcs[func_id];
245 pFunc = g_PluginSys.GetFunctionFromPool(save, this);
246 m_priv_funcs[func_id] = pFunc;
253 IPluginFunction *CPlugin::GetFunctionByName(const char *public_name)
256 IPluginContext *base = m_ctx.base;
258 if (base->FindPublicByName(public_name, &index) != SP_ERROR_NONE)
263 CFunction *pFunc = m_pub_funcs[index];
266 sp_public_t *pub = NULL;
267 base->GetPublicByIndex(index, &pub);
270 pFunc = g_PluginSys.GetFunctionFromPool(pub->funcid, this);
271 m_pub_funcs[index] = pFunc;
278 void CPlugin::UpdateInfo()
280 /* Now grab the info */
282 IPluginContext *base = GetBaseContext();
283 int err = base->FindPubvarByName("myinfo", &idx);
285 if (err == SP_ERROR_NONE)
287 struct sm_plugininfo_c_t
295 sm_plugininfo_c_t *cinfo;
298 base->GetPubvarAddrs(idx, &local_addr, (cell_t **)&cinfo);
299 base->LocalToString(cinfo->name, (char **)&m_info.name);
300 base->LocalToString(cinfo->description, (char **)&m_info.description);
301 base->LocalToString(cinfo->author, (char **)&m_info.author);
302 base->LocalToString(cinfo->url, (char **)&m_info.url);
303 base->LocalToString(cinfo->version, (char **)&m_info.version);
306 m_info.author = m_info.author ? m_info.author : "";
307 m_info.description = m_info.description ? m_info.description : "";
308 m_info.name = m_info.name ? m_info.name : "";
309 m_info.url = m_info.url ? m_info.url : "";
310 m_info.version = m_info.version ? m_info.version : "";
313 void CPlugin::Call_OnPluginInit()
315 if (m_status != Plugin_Loaded)
320 m_status = Plugin_Running;
324 IPluginFunction *pFunction = GetFunctionByName("OnPluginInit");
330 /* :TODO: push our own handle */
331 pFunction->PushCell(0);
332 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
334 /* :TODO: log into debugger instead */
335 SetErrorState(Plugin_Error, "Runtime error %d", err);
339 bool CPlugin::Call_AskPluginLoad(char *error, size_t maxlength)
341 if (m_status != Plugin_Created)
349 maxlength = sizeof(m_errormsg);
352 m_status = Plugin_Loaded;
356 IPluginFunction *pFunction = GetFunctionByName("AskPluginLoad");
363 pFunction->PushCell(0); //:TODO: handle to ourself
364 pFunction->PushCell(g_PluginSys.IsLateLoadTime() ? 1 : 0);
365 pFunction->PushStringEx(error, maxlength, 0, SM_PARAM_COPYBACK);
366 pFunction->PushCell(maxlength);
367 if ((err=pFunction->Execute(&result)) != SP_ERROR_NONE)
369 /* :TODO: debugging system */
370 snprintf(error, maxlength, "Plugin load returned run time error %d", err);
371 m_status = Plugin_Error;
377 m_status = Plugin_Error;
384 const sp_plugin_t *CPlugin::GetPluginStructure() const
389 IPluginContext *CPlugin::GetBaseContext() const
394 sp_context_t *CPlugin::GetContext() const
399 const char *CPlugin::GetFilename() const
404 PluginType CPlugin::GetType() const
409 const sm_plugininfo_t *CPlugin::GetPublicInfo() const
414 unsigned int CPlugin::GetSerial() const
419 PluginStatus CPlugin::GetStatus() const
424 bool CPlugin::IsDebugging() const
431 return ((m_ctx.ctx->flags & SP_FLAG_DEBUG) == SP_FLAG_DEBUG);
434 bool CPlugin::SetPauseState(bool paused)
436 if (paused && GetStatus() != Plugin_Paused)
439 } else if (!paused && GetStatus() != Plugin_Running) {
443 /* :TODO: execute some forwards or some crap */
448 IdentityToken_t CPlugin::GetIdentity()
457 CPluginManager::CPluginIterator::CPluginIterator(List<CPlugin *> *_mylist)
463 IPlugin *CPluginManager::CPluginIterator::GetPlugin()
468 bool CPluginManager::CPluginIterator::MorePlugins()
470 return (current != mylist->end());
473 void CPluginManager::CPluginIterator::NextPlugin()
478 void CPluginManager::CPluginIterator::Release()
480 g_PluginSys.ReleaseIterator(this);
483 CPluginManager::CPluginIterator::~CPluginIterator()
487 void CPluginManager::CPluginIterator::Reset()
489 current = mylist->begin();
496 CPluginManager::CPluginManager()
498 m_LoadLookup = sm_trie_create();
499 m_AllPluginsLoaded = false;
502 CPluginManager::~CPluginManager()
504 //:TODO: we need a good way to free what we're holding
505 sm_trie_destroy(m_LoadLookup);
509 void CPluginManager::LoadAll_FirstPass(const char *config, const char *basedir)
511 /* First read in the database of plugin settings */
513 unsigned int line, col;
514 m_AllPluginsLoaded = false;
515 if ((err=g_TextParse.ParseFile_SMC(config, &m_PluginInfo, &line, &col)) != SMCParse_Okay)
517 /* :TODO: log the error, don't bail out though */
520 LoadPluginsFromDir(basedir, NULL);
523 void CPluginManager::LoadPluginsFromDir(const char *basedir, const char *localpath)
525 char base_path[PLATFORM_MAX_PATH+1];
527 /* Form the current path to start reading from */
528 if (localpath == NULL)
530 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s", basedir);
532 g_LibSys.PathFormat(base_path, sizeof(base_path), "%s/%s", basedir, localpath);
535 IDirectory *dir = g_LibSys.OpenDirectory(base_path);
539 //:TODO: write a logger and LOG THIS UP, BABY
540 //g_LibSys.GetPlatformError(error, err_max);
544 while (dir->MoreFiles())
546 if (dir->IsEntryDirectory()
547 && (strcmp(dir->GetEntryName(), ".") != 0)
548 && (strcmp(dir->GetEntryName(), "..") != 0)
549 && (strcmp(dir->GetEntryName(), "disabled") != 0)
550 && (strcmp(dir->GetEntryName(), "optional") != 0))
552 char new_local[PLATFORM_MAX_PATH+1];
553 if (localpath == NULL)
555 /* If no path yet, don't add a former slash */
556 snprintf(new_local, sizeof(new_local), "%s", dir->GetEntryName());
558 g_LibSys.PathFormat(new_local, sizeof(new_local), "%s/%s", localpath, dir->GetEntryName());
560 LoadPluginsFromDir(basedir, new_local);
561 } else if (dir->IsEntryFile()) {
562 const char *name = dir->GetEntryName();
563 size_t len = strlen(name);
565 && strcmp(&name[len-4], ".smx") == 0)
567 /* If the filename matches, load the plugin */
568 char plugin[PLATFORM_MAX_PATH+1];
569 if (localpath == NULL)
571 snprintf(plugin, sizeof(plugin), "%s", name);
573 g_LibSys.PathFormat(plugin, sizeof(plugin), "%s/%s", localpath, name);
575 LoadAutoPlugin(plugin);
580 g_LibSys.CloseDirectory(dir);
583 //well i have discovered that gabe newell is very fat, so i wrote this comment now
584 //:TODO: remove this function, create a better wrapper for LoadPlugin()/LoadAutoPlugin()
585 void CPluginManager::LoadAutoPlugin(const char *file)
588 * Does this plugin already exist?
591 if (sm_trie_retrieve(m_LoadLookup, file, (void **)&pPlugin))
593 /* First check the type */
594 PluginType type = pPlugin->GetType();
595 if (type == PluginType_Private
596 || type == PluginType_Global)
600 /* Check to see if we should try reloading it */
601 if (pPlugin->GetStatus() == Plugin_BadLoad
602 || pPlugin->GetStatus() == Plugin_Error)
604 UnloadPlugin(pPlugin);
608 pPlugin = CPlugin::CreatePlugin(file, NULL, 0);
610 assert(pPlugin != NULL);
612 pPlugin->m_type = PluginType_MapUpdated;
614 ICompilation *co = NULL;
616 if (pPlugin->m_status == Plugin_Uncompiled)
618 co = pPlugin->StartMyCompile(g_pVM);
621 PluginSettings *pset;
622 unsigned int setcount = m_PluginInfo.GetSettingsNum();
623 for (unsigned int i=0; i<setcount; i++)
625 pset = m_PluginInfo.GetSettingsIfMatch(i, file);
630 pPlugin->m_type = pset->type_val;
633 for (unsigned int j=0; j<pset->opts_num; j++)
635 const char *key, *val;
636 m_PluginInfo.GetOptionsForPlugin(pset, j, &key, &val);
641 if (!g_pVM->SetCompilationOption(co, key, val))
643 pPlugin->SetErrorState(Plugin_Error, "Unable to set option (key \"%s\") (value \"%s\")", key, val);
644 pPlugin->CancelMyCompile();
654 pPlugin->FinishMyCompile(NULL, 0);
658 /* We don't care about the return value */
659 if (pPlugin->GetStatus() == Plugin_Created)
661 AddCoreNativesToPlugin(pPlugin);
662 pPlugin->Call_AskPluginLoad(NULL, 0);
668 IPlugin *CPluginManager::LoadPlugin(const char *path, bool debug, PluginType type, char error[], size_t err_max)
670 /* See if this plugin is already loaded... reformat to get sep chars right */
671 char checkpath[PLATFORM_MAX_PATH+1];
672 g_LibSys.PathFormat(checkpath, sizeof(checkpath), "%s", path);
675 * In manually loading a plugin, any sort of load error causes a deletion.
676 * This is because it's assumed manually loaded plugins will not be managed.
677 * For managed plugins, we need the UI to report them properly.
681 if (sm_trie_retrieve(m_LoadLookup, checkpath, (void **)&pPlugin))
683 snprintf(error, err_max, "Plugin file is already loaded");
687 pPlugin = CPlugin::CreatePlugin(path, error, err_max);
694 ICompilation *co = pPlugin->StartMyCompile(g_pVM);
695 if (!co || (debug && !g_pVM->SetCompilationOption(co, "debug", "1")))
697 snprintf(error, err_max, "Unable to start%s compilation", debug ? " debug" : "");
698 pPlugin->CancelMyCompile();
703 if (!pPlugin->FinishMyCompile(error, err_max))
709 pPlugin->m_type = type;
711 AddCoreNativesToPlugin(pPlugin);
713 /* Finally, ask the plugin if it wants to be loaded */
714 if (!pPlugin->Call_AskPluginLoad(error, err_max))
725 void CPluginManager::AddPlugin(CPlugin *pPlugin)
727 m_plugins.push_back(pPlugin);
728 sm_trie_insert(m_LoadLookup, pPlugin->m_filename, pPlugin);
730 List<IPluginsListener *>::iterator iter;
731 IPluginsListener *pListener;
732 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
735 pListener->OnPluginCreated(pPlugin);
738 /* If the second pass was already completed, we have to run the pass on this plugin */
739 if (m_AllPluginsLoaded && pPlugin->GetStatus() == Plugin_Loaded)
741 RunSecondPass(pPlugin);
745 void CPluginManager::LoadAll_SecondPass()
747 List<CPlugin *>::iterator iter;
750 for (iter=m_plugins.begin(); iter!=m_plugins.end(); iter++)
753 if (pPlugin->GetStatus() == Plugin_Loaded)
755 RunSecondPass(pPlugin);
758 m_AllPluginsLoaded = true;
761 void CPluginManager::RunSecondPass(CPlugin *pPlugin)
763 /* Tell this plugin to finish initializing itself */
764 pPlugin->Call_OnPluginInit();
766 /* Finish by telling all listeners */
767 List<IPluginsListener *>::iterator iter;
768 IPluginsListener *pListener;
769 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
772 pListener->OnPluginLoaded(pPlugin);
776 void CPluginManager::AddCoreNativesToPlugin(CPlugin *pPlugin)
778 List<sp_nativeinfo_t *>::iterator iter;
780 for (iter=m_natives.begin(); iter!=m_natives.end(); iter++)
782 sp_nativeinfo_t *natives = (*iter);
783 IPluginContext *ctx = pPlugin->GetBaseContext();
785 /* Attempt to bind every native! */
786 while (natives[i].func != NULL)
788 ctx->BindNative(&natives[i++]);
793 bool CPluginManager::UnloadPlugin(IPlugin *plugin)
795 CPlugin *pPlugin = (CPlugin *)plugin;
799 List<IPluginsListener *>::iterator iter;
800 IPluginsListener *pListener;
801 for (iter=m_listeners.begin(); iter!=m_listeners.end(); iter++)
804 pListener->OnPluginDestroyed(pPlugin);
807 m_plugins.remove(pPlugin);
808 sm_trie_delete(m_LoadLookup, pPlugin->m_filename);
815 IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
817 IPlugin *pl = (IPlugin *)ctx->user[SM_CONTEXTVAR_MYSELF];
821 unsigned int CPluginManager::GetPluginCount()
823 return m_plugins.size();
826 void CPluginManager::AddPluginsListener(IPluginsListener *listener)
828 m_listeners.push_back(listener);
831 void CPluginManager::RemovePluginsListener(IPluginsListener *listener)
833 m_listeners.remove(listener);
836 IPluginIterator *CPluginManager::GetPluginIterator()
840 return new CPluginIterator(&m_plugins);
842 CPluginIterator *iter = m_iters.front();
849 void CPluginManager::ReleaseIterator(CPluginIterator *iter)
854 void CPluginManager::ReleaseFunctionToPool(CFunction *func)
861 m_funcpool.push(func);
864 CFunction *CPluginManager::GetFunctionFromPool(funcid_t f, CPlugin *plugin)
866 if (m_funcpool.empty())
868 return new CFunction(f, plugin);
870 CFunction *func = m_funcpool.front();
872 func->Set(f, plugin);
877 bool CPluginManager::TestAliasMatch(const char *alias, const char *localpath)
879 /* As an optimization, we do not call strlen, but compute the length in the first pass */
880 size_t alias_len = 0;
881 size_t local_len = 0;
883 const char *ptr = alias;
884 unsigned int alias_explicit_paths = 0;
885 unsigned int alias_path_end = 0;
888 if (*ptr == '\\' || *ptr == '/')
890 alias_explicit_paths++;
891 alias_path_end = alias_len;
897 if (alias_explicit_paths && alias_path_end == alias_len - 1)
899 /* Trailing slash is totally invalid here */
904 unsigned int local_explicit_paths = 0;
905 unsigned int local_path_end = 0;
908 if (*ptr == '\\' || *ptr == '/')
910 local_explicit_paths++;
911 local_path_end = local_len;
917 /* If the alias has more explicit paths than the real path,
918 * no match will be possible.
920 if (alias_explicit_paths > local_explicit_paths)
925 if (alias_explicit_paths)
927 /* We need to find if the paths match now. For example, these should all match:
930 * csdm/ban optional/crab/csdm/ban
932 const char *aliasptr = alias;
933 const char *localptr = localpath;
937 if (*aliasptr != *localptr)
939 /* We have to knock one path off */
940 local_explicit_paths--;
941 if (alias_explicit_paths > local_explicit_paths)
943 /* Skip out if we're gonna have an impossible match */
946 /* Eat up localptr tokens until we get a result */
947 while (((localptr - localpath) < (int)local_path_end)
949 && *localptr != '\\')
953 /* Check if we hit the end of our searchable area.
954 * This probably isn't possible because of the path
955 * count check, but it's a good idea anyway.
957 if ((localptr - localpath) >= (int)local_path_end)
961 /* Consume the slash token */
964 /* Reset the alias pointer so we can continue consuming */
970 * This is safe because if localptr terminates early, aliasptr will too
974 /* We should never reach the end of the string because of this check. */
975 bool aliasend = (aliasptr - alias) > (int)alias_path_end;
976 bool localend = (localptr - localpath) > (int)local_path_end;
977 if (aliasend || localend)
979 if (aliasend && localend)
981 /* we matched, and we can break out now */
985 /* Otherwise, we've hit the end somehow and rest won't match up. Break out. */
990 /* If we got here, it's safe to compare the next two tokens */
991 if (*localptr != *aliasptr)
1002 /* If we got here, it's time to compare filenames */
1003 const char *aliasptr = alias;
1004 const char *localptr = localpath;
1006 if (alias_explicit_paths)
1008 aliasptr = &alias[alias_path_end + 1];
1011 if (local_explicit_paths)
1013 localptr = &localpath[local_path_end + 1];
1018 if (*aliasptr == '*')
1020 /* First, see if this is the last character */
1021 if (aliasptr - alias == alias_len - 1)
1023 /* If so, there's no need to match anything else */
1026 /* Otherwise, we need to search for an appropriate matching sequence in local.
1027 * Note that we only need to search up to the next asterisk.
1031 const char *local_orig = localptr;
1035 while (*aliasptr != '\0' && *aliasptr != '*')
1037 /* Since aliasptr is never '\0', localptr hitting the end will fail */
1038 if (*aliasptr != *localptr)
1048 /* If we didn't get a match, we need to advance the search stream.
1049 * This will let us skip tokens while still searching for another match.
1051 localptr = ++local_orig;
1052 /* Make sure we don't go out of bounds */
1053 if (*localptr == '\0')
1064 /* If we got a match, move on to the next token */
1067 } else if (*aliasptr == '\0') {
1068 if (*localptr == '\0'
1070 strcmp(localptr, ".smx") == 0)
1076 } else if (*aliasptr != *localptr) {
1086 bool CPluginManager::IsLateLoadTime()
1088 return (m_AllPluginsLoaded || g_SourceMod.IsLateLoadInMap());
1091 void CPluginManager::OnSourceModAllInitialized()
1095 sec.owner = 1; /* :TODO: implement ShareSys */
1096 sec.all.canCreate = false;
1097 sec.all.canDelete = false;
1098 sec.all.canInherit = false;
1100 g_PluginType = g_HandleSys.CreateTypeEx("IPlugin", this, 0, &sec);
1103 void CPluginManager::OnSourceModShutdown()
1105 g_HandleSys.RemoveType(g_PluginType, 1);
1108 void CPluginManager::OnHandleDestroy(HandleType_t type, void *object)
1110 /* We don't care about the internal object, actually */