Added preliminary support for Left 4 Dead; some things may not yet work.
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
32 #include "ConVarManager.h"
33 #include "HalfLife2.h"
34 #include "PluginSys.h"
35 #include "ForwardSys.h"
36 #include "HandleSys.h"
37 #include "sm_srvcmds.h"
38 #include "sm_stringutil.h"
39 #include <sh_vector.h>
40 #include <sm_trie_tpl.h>
42 ConVarManager g_ConVarManager;
44 #if SOURCE_ENGINE == SE_EPISODEONE
45 #define CallGlobalChangeCallbacks CallGlobalChangeCallback
48 #if SOURCE_ENGINE >= SE_ORANGEBOX
49 SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
51 SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *);
54 SH_DECL_HOOK1_void(ICvar, InstallGlobalChangeCallback, SH_NOATTRIB, false, FnChangeCallback_t);
56 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
57 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
59 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
60 typedef List<const ConVar *> ConVarList;
61 KTrie<ConVarInfo *> convar_cache;
63 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
67 ConVarManager::~ConVarManager()
71 void ConVarManager::OnSourceModStartup(bool late)
75 /* Set up access rights for the 'ConVar' handle type */
76 sec.access[HandleAccess_Read] = 0;
77 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
78 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
80 /* Create the 'ConVar' handle type */
81 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
84 bool GetFileOfAddress(void *pAddr, char *buffer, size_t maxlength)
86 #if defined WIN32 || defined _WIN32
87 MEMORY_BASIC_INFORMATION mem;
88 if (!VirtualQuery(pAddr, &mem, sizeof(mem)))
90 if (mem.AllocationBase == NULL)
92 HMODULE dll = (HMODULE)mem.AllocationBase;
93 GetModuleFileName(dll, (LPTSTR)buffer, maxlength);
94 #elif defined __linux__
96 if (!dladdr(pAddr, &info))
98 if (!info.dli_fbase || !info.dli_fname)
100 const char *dllpath = info.dli_fname;
101 snprintf(buffer, maxlength, "%s", dllpath);
106 void InstallCallback(FnChangeCallback_t callback)
109 GetFileOfAddress((void *)callback, path, sizeof(path));
110 printf("Yo: %s\n", path);
113 void ConVarManager::OnSourceModAllInitialized()
116 * Episode 2 has this function by default, but the older versions do not.
118 #if SOURCE_ENGINE == SE_EPISODEONE
119 if (g_SMAPI->GetGameDLLVersion() >= 6)
121 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
122 m_bIsDLLQueryHooked = true;
126 SH_ADD_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, OnConVarChanged, false);
127 SH_ADD_HOOK_STATICFUNC(ICvar, InstallGlobalChangeCallback, icvar, InstallCallback, false);
129 /* Add the 'convars' option to the 'sm' console command */
130 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
133 void ConVarManager::OnSourceModShutdown()
135 List<ConVarInfo *>::iterator iter = m_ConVars.begin();
136 HandleSecurity sec(NULL, g_pCoreIdent);
138 /* Iterate list of ConVarInfo structures, remove every one of them */
139 while (iter != m_ConVars.end())
141 ConVarInfo *pInfo = (*iter);
143 iter = m_ConVars.erase(iter);
145 g_HandleSys.FreeHandle(pInfo->handle, &sec);
146 if (pInfo->pChangeForward != NULL)
148 g_Forwards.ReleaseForward(pInfo->pChangeForward);
150 if (pInfo->sourceMod)
152 /* If we created it, we won't be tracking it, therefore it is
153 * safe to remove everything in one go.
155 META_UNREGCVAR(pInfo->pVar);
156 delete [] pInfo->pVar->GetName();
157 delete [] pInfo->pVar->GetHelpText();
158 delete [] pInfo->pVar->GetDefault();
163 /* If we didn't create it, we might be tracking it. Also,
164 * it could be unreadable.
166 UntrackConCommandBase(pInfo->pVar, this);
169 /* It's not safe to read the name here, so we simply delete the
170 * the info struct and clear the lookup cache at the end.
174 convar_cache.clear();
177 if (m_bIsDLLQueryHooked)
179 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
180 m_bIsDLLQueryHooked = false;
182 else if (m_bIsVSPQueryHooked)
184 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
185 m_bIsVSPQueryHooked = false;
188 SH_REMOVE_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, OnConVarChanged, false);
190 /* Remove the 'convars' option from the 'sm' console command */
191 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
193 /* Remove the 'ConVar' handle type */
194 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
198 * Orange Box will never use this.
200 void ConVarManager::OnSourceModVSPReceived()
203 * Don't bother if the DLL is already hooked.
205 if (m_bIsDLLQueryHooked)
210 /* For later MM:S versions, use the updated API, since it's cleaner. */
211 #if defined METAMOD_PLAPI_VERSION
212 int engine = g_SMAPI->GetSourceEngineBuild();
213 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
218 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
224 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
225 m_bIsVSPQueryHooked = true;
228 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
230 ConVarInfo **pLookup = convar_cache.retrieve(name);
242 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
244 /* Only check convars that have not been created by SourceMod's core */
246 if (!convar_cache_lookup(name, &pInfo))
251 HandleSecurity sec(NULL, g_pCoreIdent);
253 /* Remove it from our cache */
254 m_ConVars.remove(pInfo);
255 convar_cache.remove(name);
257 /* Now make sure no plugins are referring to this pointer */
258 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
259 while (pl_iter->MorePlugins())
261 IPlugin *pl = pl_iter->GetPlugin();
263 ConVarList *pConVarList;
264 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
265 && pConVarList != NULL)
267 pConVarList->remove(pInfo->pVar);
270 pl_iter->NextPlugin();
274 g_HandleSys.FreeHandle(pInfo->handle, &sec);
278 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
280 ConVarList *pConVarList;
282 /* If plugin has a convar list, free its memory */
283 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
289 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
293 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
295 *pSize = sizeof(ConVar) + sizeof(ConVarInfo);
299 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
301 int argcount = command.ArgC();
304 /* Get plugin index that was passed */
305 const char *arg = command.Arg(2);
307 /* Get plugin object */
308 CPlugin *plugin = g_PluginSys.FindPluginByConsoleArg(arg);
312 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
316 /* Get plugin name */
317 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
318 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
320 ConVarList *pConVarList;
321 ConVarList::iterator iter;
323 /* If no convar list... */
324 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
326 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
330 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
331 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
333 /* Iterate convar list and display each one */
334 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
336 const ConVar *pConVar = (*iter);
337 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
343 /* Display usage of subcommand */
344 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
347 Handle_t ConVarManager::CreateConVar(IPluginContext *pContext, const char *name, const char *defaultVal, const char *description, int flags, bool hasMin, float min, bool hasMax, float max)
349 ConVar *pConVar = NULL;
350 ConVarInfo *pInfo = NULL;
353 /* Find out if the convar exists already */
354 pConVar = icvar->FindVar(name);
356 /* If the convar already exists... */
359 /* Add convar to plugin's list */
360 AddConVarToPluginList(pContext, pConVar);
362 /* First find out if we already have a handle to it */
363 if (convar_cache_lookup(name, &pInfo))
365 return pInfo->handle;
369 /* Create and initialize ConVarInfo structure */
370 pInfo = new ConVarInfo();
371 pInfo->sourceMod = false;
372 pInfo->pChangeForward = NULL;
373 pInfo->pVar = pConVar;
375 /* If we don't, then create a new handle from the convar */
376 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
377 if (hndl == BAD_HANDLE)
383 pInfo->handle = hndl;
385 /* Insert struct into caches */
386 m_ConVars.push_back(pInfo);
387 convar_cache.insert(name, pInfo);
388 TrackConCommandBase(pConVar, this);
394 /* Prevent creating a convar that has the same name as a console command */
395 if (FindCommand(name))
400 /* Create and initialize ConVarInfo structure */
401 pInfo = new ConVarInfo();
402 pInfo->handle = hndl;
403 pInfo->sourceMod = true;
404 pInfo->pChangeForward = NULL;
406 /* Create a handle from the new convar */
407 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
408 if (hndl == BAD_HANDLE)
414 pInfo->handle = hndl;
416 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
417 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
418 pInfo->pVar = pConVar;
420 /* Add convar to plugin's list */
421 AddConVarToPluginList(pContext, pConVar);
423 /* Insert struct into caches */
424 m_ConVars.push_back(pInfo);
425 convar_cache.insert(name, pInfo);
430 Handle_t ConVarManager::FindConVar(const char *name)
432 ConVar *pConVar = NULL;
436 /* Search for convar */
437 pConVar = icvar->FindVar(name);
439 /* If it doesn't exist, then return an invalid handle */
445 /* At this point, the convar exists. So, find out if we already have a handle */
446 if (convar_cache_lookup(name, &pInfo))
448 return pInfo->handle;
451 /* Create and initialize ConVarInfo structure */
452 pInfo = new ConVarInfo();
453 pInfo->sourceMod = false;
454 pInfo->pChangeForward = NULL;
455 pInfo->pVar = pConVar;
457 /* If we don't have a handle, then create a new one */
458 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
459 if (hndl == BAD_HANDLE)
465 pInfo->handle = hndl;
467 /* Insert struct into our caches */
468 m_ConVars.push_back(pInfo);
469 convar_cache.insert(name, pInfo);
470 TrackConCommandBase(pConVar, this);
475 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
479 if (FindConVar(name) == BAD_HANDLE)
484 /* Find the convar in the lookup trie */
485 if (convar_cache_lookup(name, &pInfo))
487 pInfo->changeListeners.push_back(pListener);
491 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
495 /* Find the convar in the lookup trie */
496 if (convar_cache_lookup(name, &pInfo))
498 pInfo->changeListeners.remove(pListener);
502 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
505 IChangeableForward *pForward;
507 /* Find the convar in the lookup trie */
508 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
510 /* Get the forward */
511 pForward = pInfo->pChangeForward;
513 /* If forward does not exist, create it */
516 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
517 pInfo->pChangeForward = pForward;
520 /* Add function to forward's list */
521 pForward->AddFunction(pFunction);
525 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
528 IChangeableForward *pForward;
529 IPluginContext *pContext = pFunction->GetParentContext();
531 /* Find the convar in the lookup trie */
532 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
534 /* Get the forward */
535 pForward = pInfo->pChangeForward;
537 /* If the forward doesn't exist, we can't unhook anything */
540 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
544 /* Remove the function from the forward's list */
545 if (!pForward->RemoveFunction(pFunction))
547 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
551 /* If the forward now has 0 functions in it... */
552 if (pForward->GetFunctionCount() == 0)
554 /* Free this forward */
555 g_Forwards.ReleaseForward(pForward);
556 pInfo->pChangeForward = NULL;
561 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
563 QueryCvarCookie_t cookie;
565 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
566 if (m_bIsDLLQueryHooked)
568 cookie = engine->StartQueryCvarValue(pPlayer, name);
570 else if (m_bIsVSPQueryHooked)
572 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
576 return InvalidQueryCvarCookie;
579 ConVarQuery query = {cookie, pCallback, hndl};
580 m_ConVarQueries.push_back(query);
585 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
587 ConVarList *pConVarList;
588 ConVarList::iterator iter;
589 bool inserted = false;
590 const char *orig = pConVar->GetName();
592 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
594 /* Check plugin for an existing convar list */
595 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
597 pConVarList = new ConVarList();
598 plugin->SetProperty("ConVarList", pConVarList);
600 else if (pConVarList->find(pConVar) != pConVarList->end())
602 /* If convar is already in list, then don't add it */
606 /* Insert convar into list which is sorted alphabetically */
607 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
609 if (strcmp(orig, (*iter)->GetName()) < 0)
611 pConVarList->insert(iter, pConVar);
619 pConVarList->push_back(pConVar);
623 #if SOURCE_ENGINE >= SE_ORANGEBOX
624 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
626 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
629 /* If the values are the same, exit early in order to not trigger callbacks */
630 if (strcmp(pConVar->GetString(), oldValue) == 0)
637 /* Find the convar in the lookup trie */
638 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
643 IChangeableForward *pForward = pInfo->pChangeForward;
645 if (pInfo->changeListeners.size() != 0)
647 for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
648 i != pInfo->changeListeners.end();
651 #if SOURCE_ENGINE >= SE_ORANGEBOX
652 (*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
654 (*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
659 if (pForward != NULL)
661 /* Now call forwards in plugins that have hooked this */
662 pForward->PushCell(pInfo->handle);
663 pForward->PushString(oldValue);
664 pForward->PushString(pConVar->GetString());
665 pForward->Execute(NULL);
669 bool ConVarManager::IsQueryingSupported()
671 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
674 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
676 IPluginFunction *pCallback = NULL;
678 List<ConVarQuery>::iterator iter;
680 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
682 ConVarQuery &query = (*iter);
683 if (query.cookie == cookie)
685 pCallback = query.pCallback;
695 pCallback->PushCell(cookie);
696 pCallback->PushCell(IndexOfEdict(pPlayer));
697 pCallback->PushCell(result);
698 pCallback->PushString(cvarName);
700 if (result == eQueryCvarValueStatus_ValueIntact)
702 pCallback->PushString(cvarValue);
706 pCallback->PushString("\0");
709 pCallback->PushCell(value);
710 pCallback->Execute(&ret);
712 m_ConVarQueries.erase(iter);
716 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
721 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)