Remove SourceHook from core

This commit is contained in:
Kenzzer 2025-08-17 16:27:26 +00:00
parent 92fb9f62dd
commit 1c5183dd18
No known key found for this signature in database
GPG Key ID: 64C3FD4332686DC1
72 changed files with 915 additions and 956 deletions

View File

@ -519,7 +519,7 @@ class SMConfig(object):
compiler.cxxincludes += [ compiler.cxxincludes += [
os.path.join(self.mms_root, 'core'), os.path.join(self.mms_root, 'core'),
os.path.join(self.mms_root, 'core', 'sourcehook'), os.path.join(self.mms_root, 'third_party', 'khook', 'include'),
] ]
for other_sdk in self.sdk_manifests: for other_sdk in self.sdk_manifests:
@ -663,21 +663,21 @@ else:
'loader/AMBuilder', 'loader/AMBuilder',
'core/AMBuilder', 'core/AMBuilder',
'core/logic/AMBuilder', 'core/logic/AMBuilder',
'extensions/bintools/AMBuilder', #'extensions/bintools/AMBuilder',
'extensions/clientprefs/AMBuilder', #'extensions/clientprefs/AMBuilder',
'extensions/curl/AMBuilder', #'extensions/curl/AMBuilder',
'extensions/cstrike/AMBuilder', #'extensions/cstrike/AMBuilder',
'extensions/dhooks/AMBuilder', #'extensions/dhooks/AMBuilder',
'extensions/geoip/AMBuilder', #'extensions/geoip/AMBuilder',
'extensions/mysql/AMBuilder', #'extensions/mysql/AMBuilder',
'extensions/pgsql/AMBuilder', #'extensions/pgsql/AMBuilder',
'extensions/regex/AMBuilder', #'extensions/regex/AMBuilder',
'extensions/sdkhooks/AMBuilder', #'extensions/sdkhooks/AMBuilder',
'extensions/sdktools/AMBuilder', #'extensions/sdktools/AMBuilder',
'extensions/sqlite/AMBuilder', #'extensions/sqlite/AMBuilder',
'extensions/tf2/AMBuilder', #'extensions/tf2/AMBuilder',
'extensions/topmenus/AMBuilder', #'extensions/topmenus/AMBuilder',
'extensions/updater/AMBuilder', #'extensions/updater/AMBuilder',
] ]
if builder.backend == 'amb2': if builder.backend == 'amb2':

View File

@ -29,13 +29,12 @@
#include <sp_vm_api.h> #include <sp_vm_api.h>
#include <IExtensionSys.h> #include <IExtensionSys.h>
#include <sh_vector.h> #include <vector>
struct edict_t; struct edict_t;
namespace SourceMod { namespace SourceMod {
using namespace SourceHook;
using namespace SourcePawn; using namespace SourcePawn;
class SMPlugin; class SMPlugin;
@ -51,8 +50,8 @@ public:
virtual IExtension *GetExtensionFromIdent(IdentityToken_t *token) = 0; virtual IExtension *GetExtensionFromIdent(IdentityToken_t *token) = 0;
virtual void BindChildPlugin(IExtension *ext, SMPlugin *plugin) = 0; virtual void BindChildPlugin(IExtension *ext, SMPlugin *plugin) = 0;
virtual void AddRawDependency(IExtension *myself, IdentityToken_t *token, void *iface) = 0; virtual void AddRawDependency(IExtension *myself, IdentityToken_t *token, void *iface) = 0;
virtual const CVector<IExtension *> *ListExtensions() = 0; virtual const std::vector<IExtension *> *ListExtensions() = 0;
virtual void FreeExtensionList(const CVector<IExtension *> *list) = 0; virtual void FreeExtensionList(const std::vector<IExtension *> *list) = 0;
virtual void CallOnCoreMapEnd() = 0; virtual void CallOnCoreMapEnd() = 0;
}; };
@ -67,13 +66,13 @@ public:
{ {
extensions_->FreeExtensionList(list_); extensions_->FreeExtensionList(list_);
} }
const CVector<IExtension *> *operator ->() const std::vector<IExtension *> *operator ->()
{ {
return list_; return list_;
} }
private: private:
IExtensionSys *extensions_; IExtensionSys *extensions_;
const CVector<IExtension *> *list_; const std::vector<IExtension *> *list_;
}; };
} // namespace SourceMod } // namespace SourceMod

View File

@ -29,12 +29,11 @@
#include <sp_vm_api.h> #include <sp_vm_api.h>
#include <IPluginSys.h> #include <IPluginSys.h>
#include <sh_vector.h> #include <vector>
#include <sh_string.h> #include <string>
namespace SourceMod { namespace SourceMod {
using namespace SourceHook;
using namespace SourcePawn; using namespace SourcePawn;
class IChangeableForward; class IChangeableForward;
@ -47,8 +46,8 @@ enum LibraryAction
struct AutoConfig struct AutoConfig
{ {
SourceHook::String autocfg; std::string autocfg;
SourceHook::String folder; std::string folder;
bool create; bool create;
}; };
@ -82,8 +81,8 @@ public:
virtual SMPlugin *FindPluginByConsoleArg(const char *text) = 0; virtual SMPlugin *FindPluginByConsoleArg(const char *text) = 0;
virtual SMPlugin *FindPluginByHandle(Handle_t hndl, HandleError *errp) = 0; virtual SMPlugin *FindPluginByHandle(Handle_t hndl, HandleError *errp) = 0;
virtual bool UnloadPlugin(IPlugin *plugin) = 0; virtual bool UnloadPlugin(IPlugin *plugin) = 0;
virtual const CVector<SMPlugin *> *ListPlugins() = 0; virtual const std::vector<SMPlugin *> *ListPlugins() = 0;
virtual void FreePluginList(const CVector<SMPlugin *> *list) = 0; virtual void FreePluginList(const std::vector<SMPlugin *> *list) = 0;
virtual void AddFunctionsToForward(const char *name, IChangeableForward *fwd) = 0; virtual void AddFunctionsToForward(const char *name, IChangeableForward *fwd) = 0;
}; };
@ -98,13 +97,13 @@ public:
{ {
scripts_->FreePluginList(list_); scripts_->FreePluginList(list_);
} }
const CVector<SMPlugin *> *operator ->() const std::vector<SMPlugin *> *operator ->()
{ {
return list_; return list_;
} }
private: private:
IScriptManager *scripts_; IScriptManager *scripts_;
const CVector<SMPlugin *> *list_; const std::vector<SMPlugin *> *list_;
}; };
} // namespace SourceMod } // namespace SourceMod

View File

@ -415,7 +415,7 @@ void RegisterInPlugin(CmdHook *hook)
void ConCmdManager::AddToCmdList(ConCmdInfo *info) void ConCmdManager::AddToCmdList(ConCmdInfo *info)
{ {
List<ConCmdInfo *>::iterator iter = m_CmdList.begin(); auto iter = m_CmdList.begin();
ConCmdInfo *pInfo; ConCmdInfo *pInfo;
bool inserted = false; bool inserted = false;
const char *orig = NULL; const char *orig = NULL;

View File

@ -43,16 +43,14 @@
#include "sm_globals.h" #include "sm_globals.h"
#include "sourcemm_api.h" #include "sourcemm_api.h"
#include <IForwardSys.h> #include <IForwardSys.h>
#include <sh_list.h> #include <list>
#include <sh_string.h> #include <string>
#include <IRootConsoleMenu.h> #include <IRootConsoleMenu.h>
#include <IAdminSystem.h> #include <IAdminSystem.h>
#include "concmd_cleaner.h" #include "concmd_cleaner.h"
#include "GameHooks.h" #include "GameHooks.h"
#include <sm_namehashset.h> #include <sm_namehashset.h>
using namespace SourceHook;
struct CmdHook; struct CmdHook;
struct ConCmdInfo; struct ConCmdInfo;
@ -137,7 +135,7 @@ struct ConCmdInfo
}; };
}; };
typedef List<ConCmdInfo *> ConCmdList; typedef std::list<ConCmdInfo *> ConCmdList;
class ConCmdManager : class ConCmdManager :
public SMGlobalClass, public SMGlobalClass,
@ -180,7 +178,7 @@ private:
bool CheckAccess(int client, const char *cmd, AdminCmdInfo *pAdmin); bool CheckAccess(int client, const char *cmd, AdminCmdInfo *pAdmin);
ConCmdInfo *FindInTrie(const char *name); ConCmdInfo *FindInTrie(const char *name);
public: public:
inline const List<ConCmdInfo *> & GetCommandList() inline const std::list<ConCmdInfo *> & GetCommandList()
{ {
return m_CmdList; return m_CmdList;
} }

View File

@ -30,7 +30,7 @@
#include "ConVarManager.h" #include "ConVarManager.h"
#include "HalfLife2.h" #include "HalfLife2.h"
#include "sm_stringutil.h" #include "sm_stringutil.h"
#include <sh_vector.h> #include <vector>
#include <sm_namehashset.h> #include <sm_namehashset.h>
#include "logic_bridge.h" #include "logic_bridge.h"
#include "sourcemod.h" #include "sourcemod.h"
@ -40,7 +40,7 @@
ConVarManager g_ConVarManager; ConVarManager g_ConVarManager;
const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String}; const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
typedef List<const ConVar *> ConVarList; typedef std::list<const ConVar *> ConVarList;
NameHashSet<ConVarInfo *, ConVarInfo::ConVarPolicy> convar_cache; NameHashSet<ConVarInfo *, ConVarInfo::ConVarPolicy> convar_cache;
enum { enum {
@ -114,7 +114,7 @@ void ConVarManager::OnSourceModAllInitialized()
void ConVarManager::OnSourceModShutdown() void ConVarManager::OnSourceModShutdown()
{ {
List<ConVarInfo *>::iterator iter = m_ConVars.begin(); auto iter = m_ConVars.begin();
HandleSecurity sec(NULL, g_pCoreIdent); HandleSecurity sec(NULL, g_pCoreIdent);
/* Iterate list of ConVarInfo structures, remove every one of them */ /* Iterate list of ConVarInfo structures, remove every one of them */
@ -217,7 +217,7 @@ void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
} }
/* Clear any references to this plugin as the convar creator */ /* Clear any references to this plugin as the convar creator */
for (List<ConVarInfo *>::iterator iter = m_ConVars.begin(); iter != m_ConVars.end(); ++iter) for (auto iter = m_ConVars.begin(); iter != m_ConVars.end(); ++iter)
{ {
ConVarInfo *pInfo = (*iter); ConVarInfo *pInfo = (*iter);
@ -230,7 +230,7 @@ void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
const IPluginRuntime * pRuntime = plugin->GetRuntime(); const IPluginRuntime * pRuntime = plugin->GetRuntime();
/* Remove convar queries for this plugin that haven't returned results yet */ /* Remove convar queries for this plugin that haven't returned results yet */
for (List<ConVarQuery>::iterator iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();) for (auto iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();)
{ {
ConVarQuery &query = (*iter); ConVarQuery &query = (*iter);
if (query.pCallback->GetParentRuntime() == pRuntime) if (query.pCallback->GetParentRuntime() == pRuntime)
@ -246,7 +246,7 @@ void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
void ConVarManager::OnClientDisconnected(int client) void ConVarManager::OnClientDisconnected(int client)
{ {
/* Remove convar queries for this client that haven't returned results yet */ /* Remove convar queries for this client that haven't returned results yet */
for (List<ConVarQuery>::iterator iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();) for (auto iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();)
{ {
ConVarQuery &query = (*iter); ConVarQuery &query = (*iter);
if (query.client == client) if (query.client == client)
@ -311,7 +311,6 @@ void ConVarManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs
const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename(); const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
ConVarList *pConVarList; ConVarList *pConVarList;
ConVarList::iterator iter;
/* If no convar list... */ /* If no convar list... */
if (!plugin->GetProperty("ConVarList", (void **)&pConVarList)) if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
@ -327,7 +326,7 @@ void ConVarManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs
} }
/* Iterate convar list and display/reset each one */ /* Iterate convar list and display/reset each one */
for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++) for (auto iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
{ {
/*const */ConVar *pConVar = const_cast<ConVar *>(*iter); /*const */ConVar *pConVar = const_cast<ConVar *>(*iter);
if (!wantReset) if (!wantReset)
@ -599,11 +598,19 @@ void ConVarManager::AddConVarToPluginList(IPlugin *plugin, const ConVar *pConVar
pConVarList = new ConVarList(); pConVarList = new ConVarList();
plugin->SetProperty("ConVarList", pConVarList); plugin->SetProperty("ConVarList", pConVarList);
} }
else if (pConVarList->find(pConVar) != pConVarList->end()) else
{ {
/* If convar is already in list, then don't add it */ /* If convar is already in list, then don't add it */
auto iterS = pConVarList->begin();
while (iterS != pConVarList->end() && (*iterS) != pConVar)
{
iterS++;
}
if (iterS != pConVarList->end())
{
return; return;
} }
}
/* Insert convar into list which is sorted alphabetically */ /* Insert convar into list which is sorted alphabetically */
for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++) for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
@ -672,9 +679,9 @@ void ConVarManager::OnClientQueryFinished(QueryCvarCookie_t cookie,
{ {
IPluginFunction *pCallback = NULL; IPluginFunction *pCallback = NULL;
cell_t value = 0; cell_t value = 0;
List<ConVarQuery>::iterator iter;
for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++) auto iter = m_ConVarQueries.begin();
for (; iter != m_ConVarQueries.end(); iter++)
{ {
ConVarQuery &query = (*iter); ConVarQuery &query = (*iter);
if (query.cookie == cookie) if (query.cookie == cookie)
@ -706,6 +713,7 @@ void ConVarManager::OnClientQueryFinished(QueryCvarCookie_t cookie,
pCallback->PushCell(value); pCallback->PushCell(value);
pCallback->Execute(&ret); pCallback->Execute(&ret);
if (iter != m_ConVarQueries.end())
m_ConVarQueries.erase(iter); m_ConVarQueries.erase(iter);
} }
} }

View File

@ -34,7 +34,7 @@
#include "sm_globals.h" #include "sm_globals.h"
#include "sourcemm_api.h" #include "sourcemm_api.h"
#include <sh_list.h> #include <list>
#include <IPluginSys.h> #include <IPluginSys.h>
#include <IForwardSys.h> #include <IForwardSys.h>
#include <IHandleSys.h> #include <IHandleSys.h>
@ -45,8 +45,6 @@
#include "PlayerManager.h" #include "PlayerManager.h"
#include <sm_hashmap.h> #include <sm_hashmap.h>
using namespace SourceHook;
class IConVarChangeListener class IConVarChangeListener
{ {
public: public:
@ -63,7 +61,7 @@ struct ConVarInfo
IChangeableForward *pChangeForward; /**< Forward associated with convar */ IChangeableForward *pChangeForward; /**< Forward associated with convar */
ConVar *pVar; /**< The actual convar */ ConVar *pVar; /**< The actual convar */
IPlugin *pPlugin; /**< Originally owning plugin */ IPlugin *pPlugin; /**< Originally owning plugin */
List<IConVarChangeListener *> changeListeners; std::list<IConVarChangeListener *> changeListeners;
struct ConVarPolicy struct ConVarPolicy
{ {
@ -175,8 +173,8 @@ private:
static void AddConVarToPluginList(IPlugin *plugin, const ConVar *pConVar); static void AddConVarToPluginList(IPlugin *plugin, const ConVar *pConVar);
private: private:
HandleType_t m_ConVarType; HandleType_t m_ConVarType;
List<ConVarInfo *> m_ConVars; std::list<ConVarInfo *> m_ConVars;
List<ConVarQuery> m_ConVarQueries; std::list<ConVarQuery> m_ConVarQueries;
}; };
extern ConVarManager g_ConVarManager; extern ConVarManager g_ConVarManager;

View File

@ -62,30 +62,34 @@
# include <unistd.h> # include <unistd.h>
#endif #endif
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
#else
SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
#endif
class GenericCommandHooker : public IConCommandLinkListener class GenericCommandHooker : public IConCommandLinkListener
{ {
#if SOURCE_ENGINE >= SE_ORANGEBOX
using CmdHook = KHook::Member<ConCommand, void, const CCommand&>;
KHook::Return<void> Dispatch(ConCommand* this_ptr, const CCommand& args)
#else
using CmdHook = KHook::Member<ConCommand, void>;
KHook::Return<void> Dispatch(ConCommand* this_ptr)
#endif
{
cell_t res = ConsoleDetours::Dispatch(this_ptr
#if SOURCE_ENGINE >= SE_ORANGEBOX
, args
#endif
);
if (res >= Pl_Handled)
return { KHook::Action::Supersede };
return { KHook::Action::Ignore };
}
struct HackInfo struct HackInfo
{ {
void **vtable; void **vtable;
int hook; CmdHook* hook;
unsigned int refcount; unsigned int refcount;
}; };
CVector<HackInfo> vtables; std::vector<HackInfo> vtables;
bool enabled; bool enabled;
SourceHook::MemFuncInfo dispatch;
inline void **GetVirtualTable(ConCommandBase *pBase)
{
return *reinterpret_cast<void***>(reinterpret_cast<char*>(pBase) +
dispatch.thisptroffs +
dispatch.vtbloffs);
}
inline bool FindVtable(void **ptr, size_t& index) inline bool FindVtable(void **ptr, size_t& index)
{ {
@ -105,15 +109,14 @@ class GenericCommandHooker : public IConCommandLinkListener
if (!pBase->IsCommand()) if (!pBase->IsCommand())
return; return;
ConCommand *cmd = (ConCommand*)pBase; ConCommand *cmd = reinterpret_cast<ConCommand*>(pBase);
void **vtable = GetVirtualTable(cmd); void **vtable = *(void***)cmd;
size_t index; size_t index;
if (!FindVtable(vtable, index)) if (!FindVtable(vtable, index))
{ {
HackInfo hack; HackInfo hack;
hack.vtable = vtable; hack.vtable = vtable;
hack.hook = SH_ADD_VPHOOK(ConCommand, Dispatch, cmd, SH_MEMBER(this, &GenericCommandHooker::Dispatch), false); hack.hook = new CmdHook(KHook::GetVtableFunction(cmd, &ConCommand::Dispatch), this, &GenericCommandHooker::Dispatch, nullptr);
hack.refcount = 1; hack.refcount = 1;
vtables.push_back(hack); vtables.push_back(hack);
} }
@ -123,28 +126,13 @@ class GenericCommandHooker : public IConCommandLinkListener
} }
} }
#if SOURCE_ENGINE >= SE_ORANGEBOX
void Dispatch(const CCommand& args)
#else
void Dispatch()
#endif
{
cell_t res = ConsoleDetours::Dispatch(META_IFACEPTR(ConCommand)
#if SOURCE_ENGINE >= SE_ORANGEBOX
, args
#endif
);
if (res >= Pl_Handled)
RETURN_META(MRES_SUPERCEDE);
}
void ReparseCommandList() void ReparseCommandList()
{ {
for (size_t i = 0; i < vtables.size(); i++) for (size_t i = 0; i < vtables.size(); i++)
vtables[i].refcount = 0; vtables[i].refcount = 0;
for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next()) for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next())
MakeHookable(iter.Get()); MakeHookable(iter.Get());
CVector<HackInfo>::iterator iter = vtables.begin(); auto iter = vtables.begin();
while (iter != vtables.end()) while (iter != vtables.end())
{ {
if ((*iter).refcount) if ((*iter).refcount)
@ -167,6 +155,7 @@ class GenericCommandHooker : public IConCommandLinkListener
* *
* See bug 4018. * See bug 4018.
*/ */
delete (*iter).hook;
iter = vtables.erase(iter); iter = vtables.erase(iter);
} }
} }
@ -177,7 +166,7 @@ class GenericCommandHooker : public IConCommandLinkListener
return; return;
ConCommand *cmd = (ConCommand*)pBase; ConCommand *cmd = (ConCommand*)pBase;
void **vtable = GetVirtualTable(cmd); void **vtable = *(void***)(cmd);
size_t index; size_t index;
if (!FindVtable(vtable, index)) if (!FindVtable(vtable, index))
@ -190,8 +179,8 @@ class GenericCommandHooker : public IConCommandLinkListener
vtables[index].refcount--; vtables[index].refcount--;
if (vtables[index].refcount == 0) if (vtables[index].refcount == 0)
{ {
SH_REMOVE_HOOK_ID(vtables[index].hook); delete vtables[index].hook;
vtables.erase(vtables.iterAt(index)); vtables.erase(vtables.begin() + index);
} }
} }
@ -202,9 +191,7 @@ public:
bool Enable() bool Enable()
{ {
SourceHook::GetFuncInfo(&ConCommand::Dispatch, dispatch); if (KHook::GetVtableIndex(&ConCommand::Dispatch) == -1)
if (dispatch.thisptroffs < 0)
{ {
logger->LogError("Command filter could not determine ConCommand layout"); logger->LogError("Command filter could not determine ConCommand layout");
return false; return false;
@ -227,7 +214,7 @@ public:
void Disable() void Disable()
{ {
for (size_t i = 0; i < vtables.size(); i++) for (size_t i = 0; i < vtables.size(); i++)
SH_REMOVE_HOOK_ID(vtables[i].hook); delete vtables[i].hook;
vtables.clear(); vtables.clear();
} }

View File

@ -41,13 +41,11 @@
#include <sourcemod_version.h> #include <sourcemod_version.h>
#include <amtl/os/am-path.h> #include <amtl/os/am-path.h>
#include <amtl/os/am-fsutil.h> #include <amtl/os/am-fsutil.h>
#include <sh_list.h> #include <list>
#include <IForwardSys.h> #include <IForwardSys.h>
#include <bridge/include/IScriptManager.h> #include <bridge/include/IScriptManager.h>
#include <bridge/include/ILogger.h> #include <bridge/include/ILogger.h>
using namespace SourceHook;
#ifdef PLATFORM_WINDOWS #ifdef PLATFORM_WINDOWS
ConVar sm_corecfgfile("sm_corecfgfile", "addons\\sourcemod\\configs\\core.cfg", 0, "SourceMod core configuration file"); ConVar sm_corecfgfile("sm_corecfgfile", "addons\\sourcemod\\configs\\core.cfg", 0, "SourceMod core configuration file");
#elif defined PLATFORM_LINUX || defined PLATFORM_APPLE #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
@ -68,11 +66,9 @@ ConVar *g_ServerCfgFile = NULL;
void CheckAndFinalizeConfigs(); void CheckAndFinalizeConfigs();
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &); KHook::Return<void> Hook_ExecDispatchPre(ConCommand*, const CCommand &cmd)
void Hook_ExecDispatchPre(const CCommand &cmd)
#else #else
SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false); KHook::Return<void> Hook_ExecDispatchPre(ConCommand*)
void Hook_ExecDispatchPre()
#endif #endif
{ {
#if SOURCE_ENGINE <= SE_DARKMESSIAH #if SOURCE_ENGINE <= SE_DARKMESSIAH
@ -85,12 +81,14 @@ void Hook_ExecDispatchPre()
{ {
g_bGotTrigger = true; g_bGotTrigger = true;
} }
return { KHook::Action::Ignore };
} }
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void Hook_ExecDispatchPost(const CCommand &cmd) KHook::Return<void> Hook_ExecDispatchPost(ConCommand*, const CCommand &cmd)
#else #else
void Hook_ExecDispatchPost() KHook::Return<void> Hook_ExecDispatchPost(ConCommand*)
#endif #endif
{ {
if (g_bGotTrigger) if (g_bGotTrigger)
@ -99,8 +97,12 @@ void Hook_ExecDispatchPost()
g_bServerExecd = true; g_bServerExecd = true;
CheckAndFinalizeConfigs(); CheckAndFinalizeConfigs();
} }
return { KHook::Action::Ignore };
} }
KHook::Virtual gExecCommandHook(&ConCommand::Dispatch, &Hook_ExecDispatchPre, &Hook_ExecDispatchPost);
void CheckAndFinalizeConfigs() void CheckAndFinalizeConfigs()
{ {
if ((g_bServerExecd || g_ServerCfgFile == NULL) && g_bGotServerStart) if ((g_bServerExecd || g_ServerCfgFile == NULL) && g_bGotServerStart)
@ -134,8 +136,7 @@ void CoreConfig::OnSourceModShutdown()
if (g_pExecPtr != NULL) if (g_pExecPtr != NULL)
{ {
SH_REMOVE_HOOK(ConCommand, Dispatch, g_pExecPtr, SH_STATIC(Hook_ExecDispatchPre), false); gExecCommandHook.Remove(g_pExecPtr);
SH_REMOVE_HOOK(ConCommand, Dispatch, g_pExecPtr, SH_STATIC(Hook_ExecDispatchPost), true);
g_pExecPtr = NULL; g_pExecPtr = NULL;
} }
} }
@ -160,8 +161,7 @@ void CoreConfig::OnSourceModLevelChange(const char *mapName)
g_pExecPtr = FindCommand("exec"); g_pExecPtr = FindCommand("exec");
if (g_pExecPtr != NULL) if (g_pExecPtr != NULL)
{ {
SH_ADD_HOOK(ConCommand, Dispatch, g_pExecPtr, SH_STATIC(Hook_ExecDispatchPre), false); gExecCommandHook.Add(g_pExecPtr);
SH_ADD_HOOK(ConCommand, Dispatch, g_pExecPtr, SH_STATIC(Hook_ExecDispatchPost), true);
} }
else else
{ {
@ -396,7 +396,7 @@ bool SM_ExecuteConfig(IPlugin *pl, AutoConfig *cfg, bool can_create)
bool file_exists = ke::file::IsFile(file); bool file_exists = ke::file::IsFile(file);
if (!file_exists && will_create) if (!file_exists && will_create)
{ {
List<const ConVar *> *convars = NULL; std::list<const ConVar *> *convars = NULL;
if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars) if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars)
{ {
/* Attempt to create it */ /* Attempt to create it */
@ -407,9 +407,8 @@ bool SM_ExecuteConfig(IPlugin *pl, AutoConfig *cfg, bool can_create)
fprintf(fp, "// ConVars for plugin \"%s\"\n", pl->GetFilename()); fprintf(fp, "// ConVars for plugin \"%s\"\n", pl->GetFilename());
fprintf(fp, "\n\n"); fprintf(fp, "\n\n");
List<const ConVar *>::iterator iter;
float x; float x;
for (iter = convars->begin(); iter != convars->end(); iter++) for (auto iter = convars->begin(); iter != convars->end(); iter++)
{ {
const ConVar *cvar = (*iter); const ConVar *cvar = (*iter);
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX

View File

@ -38,10 +38,8 @@
EventManager g_EventManager; EventManager g_EventManager;
SH_DECL_HOOK2(IGameEventManager2, FireEvent, SH_NOATTRIB, 0, bool, IGameEvent *, bool);
const ParamType GAMEEVENT_PARAMS[] = {Param_Cell, Param_String, Param_Cell}; const ParamType GAMEEVENT_PARAMS[] = {Param_Cell, Param_String, Param_Cell};
typedef List<EventHook *> EventHookList; typedef std::list<EventHook *> EventHookList;
class EventForwardFilter : public IForwardFilter class EventForwardFilter : public IForwardFilter
{ {
@ -57,27 +55,25 @@ public:
} }
}; };
EventManager::EventManager() : m_EventType(0) EventManager::EventManager() : m_EventType(0),
m_FireEvent(&IGameEventManager2::FireEvent, this, &EventManager::OnFireEvent, &EventManager::OnFireEvent_Post)
{ {
} }
EventManager::~EventManager() EventManager::~EventManager()
{ {
/* Free memory used by EventInfo structs if any */ /* Free memory used by EventInfo structs if any */
CStack<EventInfo *>::iterator iter; while (!m_FreeEvents.empty())
for (iter = m_FreeEvents.begin(); iter != m_FreeEvents.end(); iter++)
{ {
delete (*iter); delete (m_FreeEvents.top());
m_FreeEvents.pop();
} }
m_FreeEvents.popall();
} }
void EventManager::OnSourceModAllInitialized() void EventManager::OnSourceModAllInitialized()
{ {
/* Add a hook for IGameEventManager2::FireEvent() */ /* Add a hook for IGameEventManager2::FireEvent() */
SH_ADD_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent), false); m_FireEvent.Add(gameevents);
SH_ADD_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent_Post), true);
HandleAccess sec; HandleAccess sec;
@ -93,8 +89,7 @@ void EventManager::OnSourceModAllInitialized()
void EventManager::OnSourceModShutdown() void EventManager::OnSourceModShutdown()
{ {
/* Remove hook for IGameEventManager2::FireEvent() */ /* Remove hook for IGameEventManager2::FireEvent() */
SH_REMOVE_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent), false); m_FireEvent.Remove(gameevents);
SH_REMOVE_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent_Post), true);
/* Remove the 'GameEvent' handle type */ /* Remove the 'GameEvent' handle type */
handlesys->RemoveType(m_EventType, g_pCoreIdent); handlesys->RemoveType(m_EventType, g_pCoreIdent);
@ -306,7 +301,11 @@ EventHookError EventManager::UnhookEvent(const char *name, IPluginFunction *pFun
} }
/* Make sure the event was actually being hooked */ /* Make sure the event was actually being hooked */
if (pHookList->find(pHook) == pHookList->end()) auto iter = pHookList->begin();
while (iter != pHookList->end() && *iter == pHook) {
iter++;
}
if (iter == pHookList->end())
{ {
return EventHookErr_NotActive; return EventHookErr_NotActive;
} }
@ -335,7 +334,7 @@ EventInfo *EventManager::CreateEvent(IPluginContext *pContext, const char *name,
{ {
pInfo = new EventInfo(); pInfo = new EventInfo();
} else { } else {
pInfo = m_FreeEvents.front(); pInfo = m_FreeEvents.top();
m_FreeEvents.pop(); m_FreeEvents.pop();
} }
@ -382,7 +381,7 @@ void EventManager::CancelCreatedEvent(EventInfo *pInfo)
} }
/* IGameEventManager2::FireEvent hook */ /* IGameEventManager2::FireEvent hook */
bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast) KHook::Return<bool> EventManager::OnFireEvent(IGameEventManager2* this_ptr, IGameEvent *pEvent, bool bDontBroadcast)
{ {
EventHook *pHook; EventHook *pHook;
IChangeableForward *pForward; IChangeableForward *pForward;
@ -393,7 +392,7 @@ bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast)
/* The engine accepts NULL without crashing, so to prevent a crash in SM we ignore these */ /* The engine accepts NULL without crashing, so to prevent a crash in SM we ignore these */
if (!pEvent) if (!pEvent)
{ {
RETURN_META_VALUE(MRES_IGNORED, false); return { KHook::Action::Ignore, false };
} }
name = pEvent->GetName(); name = pEvent->GetName();
@ -436,7 +435,7 @@ bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast)
if (res >= Pl_Handled) if (res >= Pl_Handled)
{ {
gameevents->FreeEvent(pEvent); gameevents->FreeEvent(pEvent);
RETURN_META_VALUE(MRES_SUPERCEDE, false); return { KHook::Action::Supersede, false };
} }
} }
else else
@ -445,13 +444,13 @@ bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast)
} }
if (broadcast != bDontBroadcast) if (broadcast != bDontBroadcast)
RETURN_META_VALUE_NEWPARAMS(MRES_IGNORED, true, &IGameEventManager2::FireEvent, (pEvent, broadcast)); return KHook::Recall(KHook::Return<bool>{ KHook::Action::Ignore, true }, this_ptr, pEvent, broadcast);
RETURN_META_VALUE(MRES_IGNORED, true); return { KHook::Action::Ignore, true };
} }
/* IGameEventManager2::FireEvent post hook */ /* IGameEventManager2::FireEvent post hook */
bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast) KHook::Return<bool> EventManager::OnFireEvent_Post(IGameEventManager2*, IGameEvent *pEvent, bool bDontBroadcast)
{ {
EventHook *pHook; EventHook *pHook;
EventInfo info; EventInfo info;
@ -461,10 +460,10 @@ bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast)
/* The engine accepts NULL without crashing, so to prevent a crash in SM we ignore these */ /* The engine accepts NULL without crashing, so to prevent a crash in SM we ignore these */
if (!pEvent) if (!pEvent)
{ {
RETURN_META_VALUE(MRES_IGNORED, false); return { KHook::Action::Ignore, false };
} }
pHook = m_EventStack.front(); pHook = m_EventStack.top();
if (pHook != NULL) if (pHook != NULL)
{ {
@ -475,7 +474,7 @@ bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast)
if (pHook->postCopy) if (pHook->postCopy)
{ {
info.bDontBroadcast = bDontBroadcast; info.bDontBroadcast = bDontBroadcast;
info.pEvent = m_EventCopies.front(); info.pEvent = m_EventCopies.top();
info.pOwner = NULL; info.pOwner = NULL;
hndl = handlesys->CreateHandle(m_EventType, &info, NULL, g_pCoreIdent, NULL); hndl = handlesys->CreateHandle(m_EventType, &info, NULL, g_pCoreIdent, NULL);
@ -512,5 +511,5 @@ bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast)
m_EventStack.pop(); m_EventStack.pop();
RETURN_META_VALUE(MRES_IGNORED, true); return { KHook::Action::Ignore, true };
} }

View File

@ -35,16 +35,14 @@
#include "sm_globals.h" #include "sm_globals.h"
#include "sourcemm_api.h" #include "sourcemm_api.h"
#include <sm_namehashset.h> #include <sm_namehashset.h>
#include <sh_list.h> #include <list>
#include <sh_stack.h> #include <stack>
#include <IHandleSys.h> #include <IHandleSys.h>
#include <IForwardSys.h> #include <IForwardSys.h>
#include <IPluginSys.h> #include <IPluginSys.h>
class IClient; class IClient;
using namespace SourceHook;
struct EventInfo struct EventInfo
{ {
EventInfo() EventInfo()
@ -135,14 +133,15 @@ public:
void FireEventToClient(EventInfo *pInfo, IClient *pClient); void FireEventToClient(EventInfo *pInfo, IClient *pClient);
void CancelCreatedEvent(EventInfo *pInfo); void CancelCreatedEvent(EventInfo *pInfo);
private: // IGameEventManager2 hooks private: // IGameEventManager2 hooks
bool OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast); KHook::Return<bool> OnFireEvent(IGameEventManager2*, IGameEvent *pEvent, bool bDontBroadcast);
bool OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast); KHook::Return<bool> OnFireEvent_Post(IGameEventManager2*, IGameEvent *pEvent, bool bDontBroadcast);
private: private:
HandleType_t m_EventType; HandleType_t m_EventType;
NameHashSet<EventHook *> m_EventHooks; NameHashSet<EventHook *> m_EventHooks;
CStack<EventInfo *> m_FreeEvents; std::stack<EventInfo *> m_FreeEvents;
CStack<EventHook *> m_EventStack; std::stack<EventHook *> m_EventStack;
CStack<IGameEvent *> m_EventCopies; std::stack<IGameEvent *> m_EventCopies;
KHook::Virtual<IGameEventManager2, bool, IGameEvent*, bool> m_FireEvent;
}; };
extern EventManager g_EventManager; extern EventManager g_EventManager;

View File

@ -30,49 +30,33 @@
#include "command_args.h" #include "command_args.h"
#include "provider.h" #include "provider.h"
#if SOURCE_ENGINE >= SE_ORANGEBOX KHook::Virtual CallGlobalChangeCallback_Hook(&ICvar::CallGlobalChangeCallbacks, &GameHooks::OnConVarChanged, nullptr);
SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
#else
SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallback, SH_NOATTRIB, false, ConVar *, const char *);
#endif
#if SOURCE_ENGINE != SE_DARKMESSIAH
SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
#endif
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_HOOK1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
#else
SH_DECL_HOOK0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
#endif
SH_DECL_HOOK1_void(IServerGameClients, SetCommandClient, SH_NOATTRIB, false, int);
GameHooks::GameHooks() GameHooks::GameHooks()
: client_cvar_query_mode_(ClientCvarQueryMode::Unavailable), :
last_command_client_(-1) #if SOURCE_ENGINE != SE_DARKMESSIAH
m_GameDLLOnQueryCvarValueFinishedHook(&IServerGameDLL::OnQueryCvarValueFinished, this, &GameHooks::GameDLLOnQueryCvarValueFinished, nullptr),
m_VSPOnQueryCvarValueFinishedHook(&IServerPluginCallbacks::OnQueryCvarValueFinished, this, &GameHooks::VSPOnQueryCvarValueFinished, nullptr),
#endif
m_SetCommandClient(&IServerGameClients::SetCommandClient, this, &GameHooks::SetCommandClient, nullptr)
,client_cvar_query_mode_(ClientCvarQueryMode::Unavailable)
,last_command_client_(-1)
{ {
} }
void GameHooks::Start() void GameHooks::Start()
{ {
// Hook ICvar::CallGlobalChangeCallbacks. // Hook ICvar::CallGlobalChangeCallbacks.
#if SOURCE_ENGINE >= SE_ORANGEBOX CallGlobalChangeCallback_Hook.Add(icvar);
hooks_ += SH_ADD_HOOK(ICvar, CallGlobalChangeCallbacks, icvar, SH_STATIC(OnConVarChanged), false);
#else
hooks_ += SH_ADD_HOOK(ICvar, CallGlobalChangeCallback, icvar, SH_STATIC(OnConVarChanged), false);
#endif
// Episode 2 has this function by default, but the older versions do not. // Episode 2 has this function by default, but the older versions do not.
#if SOURCE_ENGINE == SE_EPISODEONE #if SOURCE_ENGINE == SE_EPISODEONE
if (g_SMAPI->GetGameDLLVersion() >= 6) { if (g_SMAPI->GetGameDLLVersion() >= 6) {
hooks_ += SH_ADD_HOOK(IServerGameDLL, OnQueryCvarValueFinished, gamedll, SH_MEMBER(this, &GameHooks::OnQueryCvarValueFinished), false); m_GameDLLOnQueryCvarValueFinishedHook.Add(gamedll);
client_cvar_query_mode_ = ClientCvarQueryMode::DLL; client_cvar_query_mode_ = ClientCvarQueryMode::DLL;
} }
#endif #endif
m_SetCommandClient.Add(serverClients);
hooks_ += SH_ADD_HOOK(IServerGameClients, SetCommandClient, serverClients, SH_MEMBER(this, &GameHooks::SetCommandClient), false);
} }
void GameHooks::OnVSPReceived() void GameHooks::OnVSPReceived()
@ -84,30 +68,33 @@ void GameHooks::OnVSPReceived()
return; return;
#if SOURCE_ENGINE != SE_DARKMESSIAH #if SOURCE_ENGINE != SE_DARKMESSIAH
hooks_ += SH_ADD_HOOK(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, SH_MEMBER(this, &GameHooks::OnQueryCvarValueFinished), false); m_VSPOnQueryCvarValueFinishedHook.Add(vsp_interface);
client_cvar_query_mode_ = ClientCvarQueryMode::VSP; client_cvar_query_mode_ = ClientCvarQueryMode::VSP;
#endif #endif
} }
void GameHooks::Shutdown() void GameHooks::Shutdown()
{ {
for (size_t i = 0; i < hooks_.size(); i++) CallGlobalChangeCallback_Hook.Remove(icvar);
SH_REMOVE_HOOK_ID(hooks_[i]); m_GameDLLOnQueryCvarValueFinishedHook.Remove(gamedll);
hooks_.clear(); m_SetCommandClient.Remove(serverClients);
m_VSPOnQueryCvarValueFinishedHook.Remove(vsp_interface);
client_cvar_query_mode_ = ClientCvarQueryMode::Unavailable; client_cvar_query_mode_ = ClientCvarQueryMode::Unavailable;
} }
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void GameHooks::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue) KHook::Return<void> GameHooks::OnConVarChanged(ICvar*, ConVar *pConVar, const char *oldValue, float flOldValue)
#else #else
void GameHooks::OnConVarChanged(ConVar *pConVar, const char *oldValue) KHook::Return<void> GameHooks::OnConVarChanged(ICvar*, ConVar *pConVar, const char *oldValue)
#endif #endif
{ {
#if SOURCE_ENGINE < SE_ORANGEBOX #if SOURCE_ENGINE < SE_ORANGEBOX
float flOldValue = atof(oldValue); float flOldValue = atof(oldValue);
#endif #endif
g_ConVarManager.OnConVarChanged(pConVar, oldValue, flOldValue); g_ConVarManager.OnConVarChanged(pConVar, oldValue, flOldValue);
return { KHook::Action::Ignore };
} }
#if SOURCE_ENGINE != SE_DARKMESSIAH #if SOURCE_ENGINE != SE_DARKMESSIAH
@ -123,6 +110,17 @@ void GameHooks::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPla
} }
#endif #endif
KHook::Return<void> GameHooks::GameDLLOnQueryCvarValueFinished(IServerGameDLL*, QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result,
const char *cvarName, const char *cvarValue) {
OnQueryCvarValueFinished(cookie, pPlayer, result, cvarName, cvarValue);
return { KHook::Action::Ignore };
}
KHook::Return<void> GameHooks::VSPOnQueryCvarValueFinished(IServerPluginCallbacks*, QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result,
const char *cvarName, const char *cvarValue) {
OnQueryCvarValueFinished(cookie, pPlayer, result, cvarName, cvarValue);
return { KHook::Action::Ignore };
}
ke::RefPtr<CommandHook> ke::RefPtr<CommandHook>
GameHooks::AddCommandHook(ConCommand *cmd, const CommandHook::Callback &callback) GameHooks::AddCommandHook(ConCommand *cmd, const CommandHook::Callback &callback)
{ {
@ -135,37 +133,39 @@ GameHooks::AddPostCommandHook(ConCommand *cmd, const CommandHook::Callback &call
return new CommandHook(cmd, callback, true); return new CommandHook(cmd, callback, true);
} }
void GameHooks::SetCommandClient(int client) KHook::Return<void> GameHooks::SetCommandClient(IServerGameClients*, int client)
{ {
last_command_client_ = client + 1; last_command_client_ = client + 1;
return { KHook::Action::Ignore };
} }
CommandHook::CommandHook(ConCommand *cmd, const Callback &callback, bool post) CommandHook::CommandHook(ConCommand *cmd, const Callback &callback, bool post)
: hook_id_(0), : callback_(callback),
callback_(callback) m_DispatchHook(&ConCommand::Dispatch, this, (post) ? nullptr : &CommandHook::Dispatch, (post) ? &CommandHook::Dispatch : nullptr)
{ {
hook_id_ = SH_ADD_HOOK(ConCommand, Dispatch, cmd, SH_MEMBER(this, &CommandHook::Dispatch), post); m_DispatchHook.Add(cmd);
} }
CommandHook::~CommandHook() CommandHook::~CommandHook()
{ {
if (hook_id_)
SH_REMOVE_HOOK_ID(hook_id_);
} }
void CommandHook::Dispatch(DISPATCH_ARGS) #if SOURCE_ENGINE >= SE_ORANGEBOX
KHook::Return<void> CommandHook::Dispatch(ConCommand*, const CCommand& command)
#else
KHook::Return<void> CommandHook::Dispatch(ConCommand*)
#endif
{ {
DISPATCH_PROLOGUE; DISPATCH_PROLOGUE
EngineArgs args(command); EngineArgs args(command);
AddRef(); AddRef();
bool rval = callback_(sCoreProviderImpl.CommandClient(), &args); bool rval = callback_(sCoreProviderImpl.CommandClient(), &args);
Release(); Release();
if (rval) if (rval)
RETURN_META(MRES_SUPERCEDE); {
} return { KHook::Action::Supersede };
}
void CommandHook::Zap() return { KHook::Action::Ignore };
{
hook_id_ = 0;
} }

View File

@ -35,6 +35,7 @@
#include <amtl/am-refcounting.h> #include <amtl/am-refcounting.h>
#include <amtl/am-vector.h> #include <amtl/am-vector.h>
#include <amtl/am-function.h> #include <amtl/am-function.h>
#include <khook.hpp>
class ConVar; class ConVar;
class CCommand; class CCommand;
@ -68,12 +69,19 @@ public:
public: public:
CommandHook(ConCommand *cmd, const Callback &callback, bool post); CommandHook(ConCommand *cmd, const Callback &callback, bool post);
~CommandHook(); ~CommandHook();
void Dispatch(DISPATCH_ARGS); #if SOURCE_ENGINE >= SE_ORANGEBOX
void Zap(); KHook::Return<void> Dispatch(ConCommand*, const CCommand&);
#else
KHook::Return<void> Dispatch(ConCommand*);
#endif
private: private:
int hook_id_;
Callback callback_; Callback callback_;
#if SOURCE_ENGINE >= SE_ORANGEBOX
KHook::Virtual<ConCommand, void, const CCommand&> m_DispatchHook;
#else
KHook::Virtual<ConCommand, void> m_DispatchHook;
#endif
}; };
class GameHooks class GameHooks
@ -97,21 +105,29 @@ public:
return last_command_client_; return last_command_client_;
} }
private: public:
// Static callback that Valve's ConVar object executes when the convar's value changes. // Static callback that Valve's ConVar object executes when the convar's value changes.
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
static void OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue); static KHook::Return<void> OnConVarChanged(ICvar*, ConVar *pConVar, const char *oldValue, float flOldValue);
#else #else
static void OnConVarChanged(ConVar *pConVar, const char *oldValue); static KHook::Return<void> OnConVarChanged(ICvar*, ConVar *pConVar, const char *oldValue);
#endif #endif
private:
// Callback for when StartQueryCvarValue() has finished. // Callback for when StartQueryCvarValue() has finished.
#if SOURCE_ENGINE != SE_DARKMESSIAH #if SOURCE_ENGINE != SE_DARKMESSIAH
void OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, void OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result,
const char *cvarName, const char *cvarValue); const char *cvarName, const char *cvarValue);
KHook::Return<void> GameDLLOnQueryCvarValueFinished(IServerGameDLL*, QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result,
const char *cvarName, const char *cvarValue);
KHook::Virtual<IServerGameDLL, void, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *> m_GameDLLOnQueryCvarValueFinishedHook;
KHook::Return<void> VSPOnQueryCvarValueFinished(IServerPluginCallbacks*, QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result,
const char *cvarName, const char *cvarValue);
KHook::Virtual<IServerPluginCallbacks, void, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *> m_VSPOnQueryCvarValueFinishedHook;
#endif #endif
void SetCommandClient(int client); KHook::Return<void> SetCommandClient(IServerGameClients*, int client);
KHook::Virtual<IServerGameClients, void, int> m_SetCommandClient;
private: private:
class HookList : public std::vector<int> class HookList : public std::vector<int>

View File

@ -756,7 +756,7 @@ void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
{ {
pFake = new DelayedFakeCliCmd; pFake = new DelayedFakeCliCmd;
} else { } else {
pFake = m_FreeCmds.front(); pFake = m_FreeCmds.top();
m_FreeCmds.pop(); m_FreeCmds.pop();
} }
@ -852,7 +852,7 @@ const ICommandArgs *CHalfLife2::PeekCommandStack()
return NULL; return NULL;
} }
return m_CommandStack.front().args; return m_CommandStack.top().args;
} }
void CHalfLife2::PopCommandStack() void CHalfLife2::PopCommandStack()
@ -863,9 +863,9 @@ void CHalfLife2::PopCommandStack()
const char *CHalfLife2::CurrentCommandName() const char *CHalfLife2::CurrentCommandName()
{ {
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
return m_CommandStack.front().args->Arg(0); return m_CommandStack.top().args->Arg(0);
#else #else
return m_CommandStack.front().cmd; return m_CommandStack.top().cmd;
#endif #endif
} }

View File

@ -32,9 +32,8 @@
#ifndef _INCLUDE_SOURCEMOD_CHALFLIFE2_H_ #ifndef _INCLUDE_SOURCEMOD_CHALFLIFE2_H_
#define _INCLUDE_SOURCEMOD_CHALFLIFE2_H_ #define _INCLUDE_SOURCEMOD_CHALFLIFE2_H_
#include <sh_list.h> #include <list>
#include <sh_string.h> #include <string>
#include <sh_tinyhash.h>
#include <am-utility.h> #include <am-utility.h>
#include <am-hashset.h> #include <am-hashset.h>
#include <am-hashmap.h> #include <am-hashmap.h>
@ -54,7 +53,6 @@ namespace SourceMod {
class ICommandArgs; class ICommandArgs;
} // namespace SourceMod } // namespace SourceMod
using namespace SourceHook;
using namespace SourceMod; using namespace SourceMod;
static const int ENTREF_MASK = (1 << 31); static const int ENTREF_MASK = (1 << 31);
@ -153,7 +151,7 @@ typedef NameHashSet<DataMapCacheInfo> DataMapCache;
struct DelayedFakeCliCmd struct DelayedFakeCliCmd
{ {
String cmd; std::string cmd;
int client; int client;
int userid; int userid;
}; };
@ -288,8 +286,8 @@ private:
int m_SayTextMsg; int m_SayTextMsg;
int m_VGUIMenu; int m_VGUIMenu;
Queue<DelayedFakeCliCmd *> m_CmdQueue; Queue<DelayedFakeCliCmd *> m_CmdQueue;
CStack<DelayedFakeCliCmd *> m_FreeCmds; std::stack<DelayedFakeCliCmd *> m_FreeCmds;
CStack<CachedCommandInfo> m_CommandStack; std::stack<CachedCommandInfo> m_CommandStack;
Queue<DelayedKickInfo> m_DelayedKicks; Queue<DelayedKickInfo> m_DelayedKicks;
void *m_pGetCommandLine; void *m_pGetCommandLine;
#if SOURCE_ENGINE == SE_CSGO #if SOURCE_ENGINE == SE_CSGO

View File

@ -43,33 +43,36 @@ bool g_in_game_log_hook = false;
static LoggerCore g_LoggerCore; static LoggerCore g_LoggerCore;
SH_DECL_HOOK1_void(IVEngineServer, LogPrint, SH_NOATTRIB, false, const char *); static KHook::Return<void> HookLogPrint(IVEngineServer*, const char *message)
static void HookLogPrint(const char *message)
{ {
g_in_game_log_hook = true; g_in_game_log_hook = true;
bool stopped = logicore.callbacks->OnLogPrint(message); bool stopped = logicore.callbacks->OnLogPrint(message);
g_in_game_log_hook = false; g_in_game_log_hook = false;
if (stopped) if (stopped)
RETURN_META(MRES_SUPERCEDE); {
return { KHook::Action::Supersede };
}
return { KHook::Action::Ignore };
} }
KHook::Virtual LogPrintHook(&IVEngineServer::LogPrint, &HookLogPrint, nullptr);
void LoggerCore::OnSourceModStartup(bool late) void LoggerCore::OnSourceModStartup(bool late)
{ {
SH_ADD_HOOK(IVEngineServer, LogPrint, engine, SH_STATIC(HookLogPrint), false); LogPrintHook.Add(engine);
} }
void LoggerCore::OnSourceModAllShutdown() void LoggerCore::OnSourceModAllShutdown()
{ {
SH_REMOVE_HOOK(IVEngineServer, LogPrint, engine, SH_STATIC(HookLogPrint), false); LogPrintHook.Remove(engine);
} }
void Engine_LogPrintWrapper(const char *msg) void Engine_LogPrintWrapper(const char *msg)
{ {
if (g_in_game_log_hook) if (g_in_game_log_hook)
{ {
ENGINE_CALL(LogPrint)(msg); LogPrintHook.CallOriginal(engine, msg);
} }
else else
{ {

View File

@ -33,11 +33,9 @@
#define _INCLUDE_SOURCEMOD_CLOGGER_H_ #define _INCLUDE_SOURCEMOD_CLOGGER_H_
#include <stdio.h> #include <stdio.h>
#include <sh_string.h> #include <string>
#include "sm_globals.h" #include "sm_globals.h"
using namespace SourceHook;
class LoggerCore : public SMGlobalClass class LoggerCore : public SMGlobalClass
{ {
public: //SMGlobalClass public: //SMGlobalClass

View File

@ -33,14 +33,11 @@
#define _INCLUDE_SOURCEMOD_MENUMANAGER_H_ #define _INCLUDE_SOURCEMOD_MENUMANAGER_H_
#include <IMenuManager.h> #include <IMenuManager.h>
#include <sh_vector.h> #include <vector>
#include <sh_stack.h>
#include <sh_list.h>
#include "sm_globals.h" #include "sm_globals.h"
#include <string> #include <string>
using namespace SourceMod; using namespace SourceMod;
using namespace SourceHook;
class MenuManager : class MenuManager :
public IMenuManager, public IMenuManager,
@ -102,7 +99,7 @@ protected:
private: private:
int m_ShowMenu; int m_ShowMenu;
IMenuStyle *m_pDefaultStyle; IMenuStyle *m_pDefaultStyle;
CVector<IMenuStyle *> m_Styles; std::vector<IMenuStyle *> m_Styles;
HandleType_t m_StyleType; HandleType_t m_StyleType;
HandleType_t m_MenuType; HandleType_t m_MenuType;
std::string m_SelectSound = ""; std::string m_SelectSound = "";

View File

@ -144,7 +144,7 @@ void CRadioStyle::OnSourceModShutdown()
while (!m_FreeDisplays.empty()) while (!m_FreeDisplays.empty())
{ {
delete m_FreeDisplays.front(); delete m_FreeDisplays.top();
m_FreeDisplays.pop(); m_FreeDisplays.pop();
} }
} }
@ -261,7 +261,7 @@ CRadioDisplay *CRadioStyle::MakeRadioDisplay(CRadioMenu *menu)
} }
else else
{ {
display = m_FreeDisplays.front(); display = m_FreeDisplays.top();
m_FreeDisplays.pop(); m_FreeDisplays.pop();
display->Reset(); display->Reset();
} }

View File

@ -39,8 +39,8 @@
#include <IPlayerHelpers.h> #include <IPlayerHelpers.h>
#include "UserMessages.h" #include "UserMessages.h"
#include "sm_fastlink.h" #include "sm_fastlink.h"
#include <sh_stack.h> #include <stack>
#include <sh_string.h> #include <string>
#include <compat_wrappers.h> #include <compat_wrappers.h>
#include "logic/common_logic.h" #include "logic/common_logic.h"
#include "AutoHandleRooter.h" #include "AutoHandleRooter.h"
@ -106,7 +106,7 @@ public:
CRadioMenuPlayer *GetRadioMenuPlayer(int client); CRadioMenuPlayer *GetRadioMenuPlayer(int client);
private: private:
CRadioMenuPlayer *m_players; CRadioMenuPlayer *m_players;
CStack<CRadioDisplay *> m_FreeDisplays; std::stack<CRadioDisplay *> m_FreeDisplays;
}; };
class CRadioDisplay : public IMenuPanel class CRadioDisplay : public IMenuPanel
@ -133,8 +133,8 @@ public: //IMenuPanel
unsigned int GetApproxMemUsage(); unsigned int GetApproxMemUsage();
bool DirectSet(const char *str); bool DirectSet(const char *str);
private: private:
String m_BufferText; std::string m_BufferText;
String m_Title; std::string m_Title;
unsigned int m_NextPos; unsigned int m_NextPos;
int keys; int keys;
}; };

View File

@ -34,15 +34,15 @@
#include "MenuStyle_Valve.h" #include "MenuStyle_Valve.h"
#include "PlayerManager.h" #include "PlayerManager.h"
#include "ConCmdManager.h" #include "ConCmdManager.h"
#include "engine/iserverplugin.h"
SH_DECL_HOOK4_void(IServerPluginHelpers, CreateMessage, SH_NOATTRIB, false, edict_t *, DIALOG_TYPE, KeyValues *, IServerPluginCallbacks *);
ValveMenuStyle g_ValveMenuStyle; ValveMenuStyle g_ValveMenuStyle;
extern const char *g_OptionNumTable[]; extern const char *g_OptionNumTable[];
extern const char *g_OptionCmdTable[]; extern const char *g_OptionCmdTable[];
CallClass<IServerPluginHelpers> *g_pSPHCC = NULL;
ValveMenuStyle::ValveMenuStyle() : m_players(new CValveMenuPlayer[256+1]) ValveMenuStyle::ValveMenuStyle() :
m_HookCreateMessage(&IServerPluginHelpers::CreateMessage, this, &ValveMenuStyle::HookCreateMessage, nullptr),
m_players(new CValveMenuPlayer[256+1])
{ {
} }
@ -66,31 +66,30 @@ bool ValveMenuStyle::OnClientCommand(int client, const char *cmdname, const CCom
void ValveMenuStyle::OnSourceModAllInitialized() void ValveMenuStyle::OnSourceModAllInitialized()
{ {
g_Players.AddClientListener(this); g_Players.AddClientListener(this);
SH_ADD_HOOK(IServerPluginHelpers, CreateMessage, serverpluginhelpers, SH_MEMBER(this, &ValveMenuStyle::HookCreateMessage), false); m_HookCreateMessage.Add(serverpluginhelpers);
g_pSPHCC = SH_GET_CALLCLASS(serverpluginhelpers);
} }
void ValveMenuStyle::OnSourceModShutdown() void ValveMenuStyle::OnSourceModShutdown()
{ {
SH_RELEASE_CALLCLASS(g_pSPHCC); m_HookCreateMessage.Remove(serverpluginhelpers);
SH_REMOVE_HOOK(IServerPluginHelpers, CreateMessage, serverpluginhelpers, SH_MEMBER(this, &ValveMenuStyle::HookCreateMessage), false);
g_Players.RemoveClientListener(this); g_Players.RemoveClientListener(this);
} }
void ValveMenuStyle::HookCreateMessage(edict_t *pEdict, KHook::Return<void> ValveMenuStyle::HookCreateMessage(IServerPluginHelpers*,
edict_t *pEdict,
DIALOG_TYPE type, DIALOG_TYPE type,
KeyValues *kv, KeyValues *kv,
IServerPluginCallbacks *plugin) IServerPluginCallbacks *plugin)
{ {
if (type != DIALOG_MENU) if (type != DIALOG_MENU)
{ {
return; return { KHook::Action::Ignore };
} }
int client = IndexOfEdict(pEdict); int client = IndexOfEdict(pEdict);
if (client < 1 || client > 256) if (client < 1 || client > 256)
{ {
return; return { KHook::Action::Ignore };
} }
CValveMenuPlayer *player = &m_players[client]; CValveMenuPlayer *player = &m_players[client];
@ -110,6 +109,7 @@ void ValveMenuStyle::HookCreateMessage(edict_t *pEdict,
*/ */
_CancelClientMenu(client, MenuCancel_Interrupted, true); _CancelClientMenu(client, MenuCancel_Interrupted, true);
} }
return { KHook::Action::Ignore };
} }
IMenuPanel *ValveMenuStyle::CreatePanel() IMenuPanel *ValveMenuStyle::CreatePanel()
@ -323,7 +323,8 @@ void CValveMenuDisplay::SendRawDisplay(int client, int priority, unsigned int ti
m_pKv->SetInt("level", priority); m_pKv->SetInt("level", priority);
m_pKv->SetInt("time", time ? time : 200); m_pKv->SetInt("time", time ? time : 200);
SH_CALL(g_pSPHCC, &IServerPluginHelpers::CreateMessage)( KHook::CallOriginal(&IServerPluginHelpers::CreateMessage,
serverpluginhelpers,
PEntityOfEntIndex(client), PEntityOfEntIndex(client),
DIALOG_MENU, DIALOG_MENU,
m_pKv, m_pKv,

View File

@ -79,7 +79,8 @@ public: //IMenuStyle
unsigned int GetApproxMemUsage(); unsigned int GetApproxMemUsage();
bool IsSupported() { return true; } bool IsSupported() { return true; }
private: private:
void HookCreateMessage(edict_t *pEdict, DIALOG_TYPE type, KeyValues *kv, IServerPluginCallbacks *plugin); KHook::Return<void> HookCreateMessage(IServerPluginHelpers*, edict_t *pEdict, DIALOG_TYPE type, KeyValues *kv, IServerPluginCallbacks *plugin);
KHook::Virtual<IServerPluginHelpers, void, edict_t*, DIALOG_TYPE, KeyValues*, IServerPluginCallbacks*> m_HookCreateMessage;
private: private:
CValveMenuPlayer *m_players; CValveMenuPlayer *m_players;
}; };

View File

@ -34,11 +34,10 @@
#include <IMenuManager.h> #include <IMenuManager.h>
#include <IPlayerHelpers.h> #include <IPlayerHelpers.h>
#include <sh_vector.h> #include <vector>
#include "sm_globals.h" #include "sm_globals.h"
#include <TimerSys.h> #include <TimerSys.h>
using namespace SourceHook;
using namespace SourceMod; using namespace SourceMod;
class VoteMenuHandler : class VoteMenuHandler :
@ -97,7 +96,7 @@ private:
unsigned int m_Clients; unsigned int m_Clients;
unsigned int m_TotalClients; unsigned int m_TotalClients;
unsigned int m_Items; unsigned int m_Items;
CVector<unsigned int> m_Votes; std::vector<unsigned int> m_Votes;
IBaseMenu *m_pCurMenu; IBaseMenu *m_pCurMenu;
bool m_bStarted; bool m_bStarted;
bool m_bCancelled; bool m_bCancelled;

View File

@ -34,7 +34,6 @@
#include "HalfLife2.h" #include "HalfLife2.h"
#include "sourcemm_api.h" #include "sourcemm_api.h"
#include "sm_stringutil.h" #include "sm_stringutil.h"
#include "sourcehook.h"
#include "logic_bridge.h" #include "logic_bridge.h"
#include "compat_wrappers.h" #include "compat_wrappers.h"
#include <time.h> #include <time.h>
@ -42,17 +41,7 @@
NextMapManager g_NextMap; NextMapManager g_NextMap;
#if SOURCE_ENGINE != SE_DARKMESSIAH KHook::Virtual gCommandDispatch(&ConCommand::Dispatch, CmdChangeLevelCallback, nullptr);
SH_DECL_HOOK2_void(IVEngineServer, ChangeLevel, SH_NOATTRIB, 0, const char *, const char *);
#else
SH_DECL_HOOK4_void(IVEngineServer, ChangeLevel, SH_NOATTRIB, 0, const char *, const char *, const char *, bool);
#endif
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
#else
SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
#endif
ConCommand *changeLevelCmd = NULL; ConCommand *changeLevelCmd = NULL;
@ -63,27 +52,25 @@ bool g_forcedChange = false;
void NextMapManager::OnSourceModAllInitialized_Post() void NextMapManager::OnSourceModAllInitialized_Post()
{ {
SH_ADD_HOOK(IVEngineServer, ChangeLevel, engine, SH_MEMBER(this, &NextMapManager::HookChangeLevel), false); m_HookChangeLevel.Add(engine);
ConCommand *pCmd = FindCommand("changelevel"); ConCommand *pCmd = FindCommand("changelevel");
if (pCmd != NULL) if (pCmd != NULL)
{ {
SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdChangeLevelCallback), false); gCommandDispatch.Add(pCmd);
changeLevelCmd = pCmd; changeLevelCmd = pCmd;
} }
} }
void NextMapManager::OnSourceModShutdown() void NextMapManager::OnSourceModShutdown()
{ {
SH_REMOVE_HOOK(IVEngineServer, ChangeLevel, engine, SH_MEMBER(this, &NextMapManager::HookChangeLevel), false); m_HookChangeLevel.Remove(engine);
if (changeLevelCmd != NULL) if (changeLevelCmd != NULL)
{ {
SH_REMOVE_HOOK(ConCommand, Dispatch, changeLevelCmd, SH_STATIC(CmdChangeLevelCallback), false); gCommandDispatch.Remove(changeLevelCmd);
} }
SourceHook::List<MapChangeData *>::iterator iter; auto iter = m_mapHistory.begin();
iter = m_mapHistory.begin();
while (iter != m_mapHistory.end()) while (iter != m_mapHistory.end())
{ {
@ -112,15 +99,15 @@ bool NextMapManager::SetNextMap(const char *map)
static char g_nextMap[PLATFORM_MAX_PATH]; static char g_nextMap[PLATFORM_MAX_PATH];
#if SOURCE_ENGINE != SE_DARKMESSIAH #if SOURCE_ENGINE != SE_DARKMESSIAH
void NextMapManager::HookChangeLevel(const char *map, const char *unknown) KHook::Return<void> NextMapManager::HookChangeLevel(IVEngineServer* this_ptr, const char *map, const char *unknown)
#else #else
void NextMapManager::HookChangeLevel(const char *map, const char *unknown, const char *video, bool bLongLoading) KHook::Return<void> NextMapManager::HookChangeLevel(IVEngineServer* this_ptr, const char *map, const char *unknown, const char *video, bool bLongLoading)
#endif #endif
{ {
if (g_forcedChange) if (g_forcedChange)
{ {
logger->LogMessage("[SM] Changed map to \"%s\"", map); logger->LogMessage("[SM] Changed map to \"%s\"", map);
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
} }
const char *newmap = sm_nextmap.GetString(); const char *newmap = sm_nextmap.GetString();
@ -135,7 +122,7 @@ void NextMapManager::HookChangeLevel(const char *map, const char *unknown, const
if (newmap[0] == '\0' || !g_HL2.IsMapValid(newmap)) if (newmap[0] == '\0' || !g_HL2.IsMapValid(newmap))
{ {
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
} }
logger->LogMessage("[SM] Changed map to \"%s\"", newmap); logger->LogMessage("[SM] Changed map to \"%s\"", newmap);
@ -144,9 +131,9 @@ void NextMapManager::HookChangeLevel(const char *map, const char *unknown, const
ke::SafeStrcpy(m_tempChangeInfo.m_changeReason, sizeof(m_tempChangeInfo.m_changeReason), "Normal level change"); ke::SafeStrcpy(m_tempChangeInfo.m_changeReason, sizeof(m_tempChangeInfo.m_changeReason), "Normal level change");
#if SOURCE_ENGINE != SE_DARKMESSIAH #if SOURCE_ENGINE != SE_DARKMESSIAH
RETURN_META_NEWPARAMS(MRES_IGNORED, &IVEngineServer::ChangeLevel, (newmap, unknown)); return KHook::Recall(KHook::Return<void>{ KHook::Action::Ignore }, this_ptr, newmap, unknown);
#else #else
RETURN_META_NEWPARAMS(MRES_IGNORED, &IVEngineServer::ChangeLevel, (newmap, unknown, video, bLongLoading)); return KHook::Recall(KHook::Return<void>{ KHook::Action::Ignore }, this_ptr, newmap, unknown, video, bLongLoading);
#endif #endif
} }
@ -186,7 +173,7 @@ void NextMapManager::OnSourceModLevelChange( const char *mapName )
historydiff = (m_mapHistory.size() * -1); historydiff = (m_mapHistory.size() * -1);
} }
for (SourceHook::List<MapChangeData *>::iterator iter = m_mapHistory.begin(); historydiff++ < 0; iter = m_mapHistory.erase(iter)) for (auto iter = m_mapHistory.begin(); historydiff++ < 0; iter = m_mapHistory.erase(iter))
{ {
delete (MapChangeData *)*iter; delete (MapChangeData *)*iter;
} }
@ -210,24 +197,24 @@ void NextMapManager::ForceChangeLevel( const char *mapName, const char* changeRe
g_forcedChange = false; g_forcedChange = false;
} }
NextMapManager::NextMapManager() NextMapManager::NextMapManager() :
m_HookChangeLevel(&IVEngineServer::ChangeLevel, this, &NextMapManager::HookChangeLevel, nullptr)
{ {
m_tempChangeInfo = MapChangeData(); m_tempChangeInfo = MapChangeData();
m_mapHistory = SourceHook::List<MapChangeData *>();
} }
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void CmdChangeLevelCallback(const CCommand &command) KHook::Return<void> CmdChangeLevelCallback(ConCommand*, const CCommand &command)
{ {
#else #else
void CmdChangeLevelCallback() KHook::Return<void> CmdChangeLevelCallback(ConCommand*)
{ {
CCommand command; CCommand command;
#endif #endif
if (command.ArgC() < 2) if (command.ArgC() < 2)
{ {
return; return { KHook::Action::Ignore };
} }
if (g_NextMap.m_tempChangeInfo.m_mapName[0] == '\0') if (g_NextMap.m_tempChangeInfo.m_mapName[0] == '\0')
@ -235,4 +222,6 @@ void CmdChangeLevelCallback()
ke::SafeStrcpy(g_NextMap.m_tempChangeInfo.m_mapName, sizeof(g_NextMap.m_tempChangeInfo.m_mapName), command.Arg(1)); ke::SafeStrcpy(g_NextMap.m_tempChangeInfo.m_mapName, sizeof(g_NextMap.m_tempChangeInfo.m_mapName), command.Arg(1));
ke::SafeStrcpy(g_NextMap.m_tempChangeInfo.m_changeReason, sizeof(g_NextMap.m_tempChangeInfo.m_changeReason), "changelevel Command"); ke::SafeStrcpy(g_NextMap.m_tempChangeInfo.m_changeReason, sizeof(g_NextMap.m_tempChangeInfo.m_changeReason), "changelevel Command");
} }
return { KHook::Action::Ignore };
} }

View File

@ -34,9 +34,10 @@
#include "sm_globals.h" #include "sm_globals.h"
#include <eiface.h> #include <eiface.h>
#include "sh_list.h" #include <list>
#include "sm_stringutil.h" #include "sm_stringutil.h"
#include <amtl/am-string.h> #include <amtl/am-string.h>
#include <khook.hpp>
struct MapChangeData struct MapChangeData
{ {
@ -60,9 +61,9 @@ struct MapChangeData
}; };
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void CmdChangeLevelCallback(const CCommand &command); KHook::Return<void> CmdChangeLevelCallback(ConCommand*, const CCommand &command);
#else #else
void CmdChangeLevelCallback(); KHook::Return<void> CmdChangeLevelCallback(ConCommand*);
#endif #endif
class NextMapManager : public SMGlobalClass class NextMapManager : public SMGlobalClass
@ -71,9 +72,9 @@ public:
NextMapManager(); NextMapManager();
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
friend void CmdChangeLevelCallback(const CCommand &command); friend KHook::Return<void> CmdChangeLevelCallback(ConCommand*, const CCommand &command);
#else #else
friend void CmdChangeLevelCallback(); friend KHook::Return<void> CmdChangeLevelCallback(ConCommand*);
#endif #endif
void OnSourceModAllInitialized_Post(); void OnSourceModAllInitialized_Post();
@ -86,13 +87,15 @@ public:
void ForceChangeLevel(const char *mapName, const char* changeReason); void ForceChangeLevel(const char *mapName, const char* changeReason);
#if SOURCE_ENGINE != SE_DARKMESSIAH #if SOURCE_ENGINE != SE_DARKMESSIAH
void HookChangeLevel(const char *map, const char *unknown); KHook::Virtual<IVEngineServer, void, const char*, const char*> m_HookChangeLevel;
KHook::Return<void> HookChangeLevel(IVEngineServer*, const char *map, const char *unknown);
#else #else
void HookChangeLevel(const char *map, const char *unknown, const char *video, bool bLongLoading); KHook::Virtual<IVEngineServer, void, const char*, const char*, const char*, bool> m_HookChangeLevel;
KHook::Return<void> HookChangeLevel(IVEngineServer*, const char *map, const char *unknown, const char *video, bool bLongLoading);
#endif #endif
public: public:
SourceHook::List<MapChangeData *> m_mapHistory; std::list<MapChangeData *> m_mapHistory;
private: private:
MapChangeData m_tempChangeInfo; MapChangeData m_tempChangeInfo;

View File

@ -64,38 +64,11 @@ IForward *ServerExitHibernation = NULL;
const unsigned int *g_NumPlayersToAuth = NULL; const unsigned int *g_NumPlayersToAuth = NULL;
int lifestate_offset = -1; int lifestate_offset = -1;
List<ICommandTargetProcessor *> target_processors; std::list<ICommandTargetProcessor *> target_processors;
ConVar sm_debug_connect("sm_debug_connect", "1", 0, "Log Debug information about potential connection issues."); ConVar sm_debug_connect("sm_debug_connect", "1", 0, "Log Debug information about potential connection issues.");
SH_DECL_HOOK5(IServerGameClients, ClientConnect, SH_NOATTRIB, 0, bool, edict_t *, const char *, const char *, char *, int); KHook::Virtual gHookCommandDispatch(&ConCommand::Dispatch, nullptr, &CmdMaxplayersCallback);
SH_DECL_HOOK2_void(IServerGameClients, ClientPutInServer, SH_NOATTRIB, 0, edict_t *, const char *);
SH_DECL_HOOK1_void(IServerGameClients, ClientDisconnect, SH_NOATTRIB, 0, edict_t *);
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
#else
SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
#endif
SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *);
#if SOURCE_ENGINE >= SE_EYE
SH_DECL_HOOK2_void(IServerGameClients, ClientCommandKeyValues, SH_NOATTRIB, 0, edict_t *, KeyValues *);
#endif
SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
#if SOURCE_ENGINE >= SE_LEFT4DEAD
SH_DECL_HOOK1_void(IServerGameDLL, ServerHibernationUpdate, SH_NOATTRIB, 0, bool);
#elif SOURCE_ENGINE > SE_EYE // 2013/orangebox, but not original orangebox.
SH_DECL_HOOK1_void(IServerGameDLL, SetServerHibernation, SH_NOATTRIB, 0, bool);
#endif
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
#else
SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
#endif
SH_DECL_HOOK2_void(IVEngineServer, ClientPrintf, SH_NOATTRIB, 0, edict_t *, const char *);
static void PrintfBuffer_FrameAction(void *data) static void PrintfBuffer_FrameAction(void *data)
{ {
@ -125,7 +98,22 @@ public:
} }
} s_KickPlayerTimer; } s_KickPlayerTimer;
PlayerManager::PlayerManager() PlayerManager::PlayerManager() :
m_HookClientConnect(&IServerGameClients::ClientConnect, this, &PlayerManager::OnClientConnect, &PlayerManager::OnClientConnect_Post),
m_HookClientPutInServer(&IServerGameClients::ClientPutInServer, this, nullptr, &PlayerManager::OnClientPutInServer),
m_HookClientDisconnect(&IServerGameClients::ClientDisconnect, this, &PlayerManager::OnClientDisconnect, &PlayerManager::OnClientDisconnect_Post),
m_HookClientCommand(&IServerGameClients::ClientCommand, this, &PlayerManager::OnClientCommand, nullptr),
#if SOURCE_ENGINE >= SE_EYE
m_HookClientCommandKeyValues(&IServerGameClients::ClientCommandKeyValues, this, &PlayerManager::OnClientCommandKeyValues, &PlayerManager::OnClientCommandKeyValues_Post),
#endif
m_HookClientSettingsChanged(&IServerGameClients::ClientSettingsChanged, this, nullptr, &PlayerManager::OnClientSettingsChanged),
m_HookServerActivate(&IServerGameDLL::ServerActivate, this, nullptr, &PlayerManager::OnServerActivate),
#if SOURCE_ENGINE >= SE_LEFT4DEAD
m_HookServerHibernationUpdate(&IServerGameDLL::ServerHibernationUpdate, this, nullptr, &PlayerManager::OnServerHibernationUpdate),
#elif SOURCE_ENGINE > SE_EYE
m_HookSetServerHibernation(&IServerGameDLL::SetServerHibernation, this, nullptr, &PlayerManager::OnServerHibernationUpdate),
#endif
m_HookClientPrintf(&IVEngineServer::ClientPrintf, this, &PlayerManager::OnClientPrintf, nullptr)
{ {
m_AuthQueue = NULL; m_AuthQueue = NULL;
m_bServerActivated = false; m_bServerActivated = false;
@ -164,24 +152,21 @@ void PlayerManager::OnSourceModStartup(bool late)
void PlayerManager::OnSourceModAllInitialized() void PlayerManager::OnSourceModAllInitialized()
{ {
SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false); m_HookClientConnect.Add(serverClients);
SH_ADD_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true); m_HookClientPutInServer.Add(serverClients);
SH_ADD_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true); m_HookClientDisconnect.Add(serverClients);
SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false); m_HookClientCommand.Add(serverClients);
SH_ADD_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
SH_ADD_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
#if SOURCE_ENGINE >= SE_EYE #if SOURCE_ENGINE >= SE_EYE
SH_ADD_HOOK(IServerGameClients, ClientCommandKeyValues, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommandKeyValues), false); m_HookClientCommandKeyValues.Add(serverClients);
SH_ADD_HOOK(IServerGameClients, ClientCommandKeyValues, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommandKeyValues_Post), true);
#endif #endif
SH_ADD_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true); m_HookClientSettingsChanged.Add(serverClients);
SH_ADD_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true); m_HookServerActivate.Add(gamedll);
#if SOURCE_ENGINE >= SE_LEFT4DEAD #if SOURCE_ENGINE >= SE_LEFT4DEAD
SH_ADD_HOOK(IServerGameDLL, ServerHibernationUpdate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerHibernationUpdate), true); m_HookServerHibernationUpdate.Add(gamedll);
#elif SOURCE_ENGINE > SE_EYE // 2013/orangebox, but not original orangebox. #elif SOURCE_ENGINE > SE_EYE // 2013/orangebox, but not original orangebox.
SH_ADD_HOOK(IServerGameDLL, SetServerHibernation, gamedll, SH_MEMBER(this, &PlayerManager::OnServerHibernationUpdate), true); m_HookSetServerHibernation.Add(gamedll);
#endif #endif
SH_ADD_HOOK(IVEngineServer, ClientPrintf, engine, SH_MEMBER(this, &PlayerManager::OnClientPrintf), false); m_HookClientPrintf.Add(engine);
sharesys->AddInterface(NULL, this); sharesys->AddInterface(NULL, this);
@ -214,31 +199,28 @@ void PlayerManager::OnSourceModAllInitialized()
ConCommand *pCmd = FindCommand("maxplayers"); ConCommand *pCmd = FindCommand("maxplayers");
if (pCmd != NULL) if (pCmd != NULL)
{ {
SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdMaxplayersCallback), true); gHookCommandDispatch.Add(pCmd);
maxplayersCmd = pCmd; maxplayersCmd = pCmd;
} }
} }
void PlayerManager::OnSourceModShutdown() void PlayerManager::OnSourceModShutdown()
{ {
SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect), false); m_HookClientConnect.Remove(serverClients);
SH_REMOVE_HOOK(IServerGameClients, ClientConnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientConnect_Post), true); m_HookClientPutInServer.Remove(serverClients);
SH_REMOVE_HOOK(IServerGameClients, ClientPutInServer, serverClients, SH_MEMBER(this, &PlayerManager::OnClientPutInServer), true); m_HookClientDisconnect.Remove(serverClients);
SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect), false); m_HookClientCommand.Remove(serverClients);
SH_REMOVE_HOOK(IServerGameClients, ClientDisconnect, serverClients, SH_MEMBER(this, &PlayerManager::OnClientDisconnect_Post), true);
SH_REMOVE_HOOK(IServerGameClients, ClientCommand, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommand), false);
#if SOURCE_ENGINE >= SE_EYE #if SOURCE_ENGINE >= SE_EYE
SH_REMOVE_HOOK(IServerGameClients, ClientCommandKeyValues, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommandKeyValues), false); m_HookClientCommandKeyValues.Remove(serverClients);
SH_REMOVE_HOOK(IServerGameClients, ClientCommandKeyValues, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommandKeyValues_Post), true);
#endif #endif
SH_REMOVE_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true); m_HookClientSettingsChanged.Remove(serverClients);
SH_REMOVE_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true); m_HookServerActivate.Remove(gamedll);
#if SOURCE_ENGINE >= SE_LEFT4DEAD #if SOURCE_ENGINE >= SE_LEFT4DEAD
SH_REMOVE_HOOK(IServerGameDLL, ServerHibernationUpdate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerHibernationUpdate), true); m_HookServerHibernationUpdate.Remove(gamedll);
#elif SOURCE_ENGINE > SE_EYE // 2013/orangebox, but not original orangebox. #elif SOURCE_ENGINE > SE_EYE // 2013/orangebox, but not original orangebox.
SH_REMOVE_HOOK(IServerGameDLL, SetServerHibernation, gamedll, SH_MEMBER(this, &PlayerManager::OnServerHibernationUpdate), true); m_HookSetServerHibernation.Remove(gamedll);
#endif #endif
SH_REMOVE_HOOK(IVEngineServer, ClientPrintf, engine, SH_MEMBER(this, &PlayerManager::OnClientPrintf), false); m_HookClientPrintf.Remove(engine);
/* Release forwards */ /* Release forwards */
forwardsys->ReleaseForward(m_clconnect); forwardsys->ReleaseForward(m_clconnect);
@ -265,7 +247,7 @@ void PlayerManager::OnSourceModShutdown()
if (maxplayersCmd != NULL) if (maxplayersCmd != NULL)
{ {
SH_REMOVE_HOOK(ConCommand, Dispatch, maxplayersCmd, SH_STATIC(CmdMaxplayersCallback), true); gHookCommandDispatch.Remove(maxplayersCmd);
} }
} }
@ -308,7 +290,7 @@ ConfigResult PlayerManager::OnSourceModConfigChanged(const char *key,
return ConfigResult_Ignore; return ConfigResult_Ignore;
} }
void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax) KHook::Return<void> PlayerManager::OnServerActivate(IServerGameDLL*, edict_t *pEdictList, int edictCount, int clientMax)
{ {
static ConVar *tv_enable = icvar->FindVar("tv_enable"); static ConVar *tv_enable = icvar->FindVar("tv_enable");
#if SOURCE_ENGINE == SE_TF2 #if SOURCE_ENGINE == SE_TF2
@ -331,8 +313,7 @@ void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int cl
m_onActivate->Execute(NULL); m_onActivate->Execute(NULL);
m_onActivate2->Execute(NULL); m_onActivate2->Execute(NULL);
List<IClientListener *>::iterator iter; for (auto iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
for (iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
{ {
if ((*iter)->GetClientListenerVersion() >= 5) if ((*iter)->GetClientListenerVersion() >= 5)
{ {
@ -348,6 +329,8 @@ void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int cl
} }
SM_ExecuteAllConfigs(); SM_ExecuteAllConfigs();
return { KHook::Action::Ignore };
} }
bool PlayerManager::IsServerActivated() bool PlayerManager::IsServerActivated()
@ -434,9 +417,8 @@ void PlayerManager::RunAuthChecks()
const char *steamId = pPlayer->GetSteam2Id(); const char *steamId = pPlayer->GetSteam2Id();
/* Send to extensions */ /* Send to extensions */
List<IClientListener *>::iterator iter;
IClientListener *pListener; IClientListener *pListener;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnClientAuthorized(client, steamId ? steamId : authstr); pListener->OnClientAuthorized(client, steamId ? steamId : authstr);
@ -492,7 +474,7 @@ void PlayerManager::RunAuthChecks()
} }
} }
bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) KHook::Return<bool> PlayerManager::OnClientConnect(IServerGameClients* clients, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
{ {
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
CPlayer *pPlayer = &m_Players[client]; CPlayer *pPlayer = &m_Players[client];
@ -511,8 +493,8 @@ bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const
logger->LogMessage("\"%s<%d><%s><>\" was already connected to the server.", pPlayer->GetName(), pPlayer->GetUserId(), pAuth); logger->LogMessage("\"%s<%d><%s><>\" was already connected to the server.", pPlayer->GetName(), pPlayer->GetUserId(), pAuth);
} }
OnClientDisconnect(pPlayer->GetEdict()); OnClientDisconnect(clients, pPlayer->GetEdict());
OnClientDisconnect_Post(pPlayer->GetEdict()); OnClientDisconnect_Post(clients, pPlayer->GetEdict());
} }
pPlayer->Initialize(pszName, pszAddress, pEntity); pPlayer->Initialize(pszName, pszAddress, pEntity);
@ -537,14 +519,13 @@ bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const
pPlayer->m_OriginalLangId = pPlayer->m_LangId; pPlayer->m_OriginalLangId = pPlayer->m_LangId;
} }
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
if (!pListener->InterceptClientConnect(client, reject, maxrejectlen)) if (!pListener->InterceptClientConnect(client, reject, maxrejectlen))
{ {
RETURN_META_VALUE(MRES_SUPERCEDE, false); return { KHook::Action::Supersede, false };
} }
} }
@ -568,30 +549,29 @@ bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const
{ {
if (!pPlayer->IsFakeClient()) if (!pPlayer->IsFakeClient())
{ {
RETURN_META_VALUE(MRES_SUPERCEDE, false); return { KHook::Action::Supersede, false };
} }
} }
return true; return { KHook::Action::Ignore, true };
} }
bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) KHook::Return<bool> PlayerManager::OnClientConnect_Post(IServerGameClients*, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
{ {
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
bool orig_value = META_RESULT_ORIG_RET(bool); bool orig_value = *(bool*)KHook::GetOriginalValuePtr();
CPlayer *pPlayer = &m_Players[client]; CPlayer *pPlayer = &m_Players[client];
if (orig_value) if (orig_value)
{ {
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnClientConnected(client); pListener->OnClientConnected(client);
if (!pPlayer->IsConnected()) if (!pPlayer->IsConnected())
{ {
return true; return { KHook::Action::Ignore };
} }
} }
@ -611,10 +591,10 @@ bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName,
InvalidatePlayer(pPlayer); InvalidatePlayer(pPlayer);
} }
return true; return { KHook::Action::Ignore };
} }
void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername) KHook::Return<void> PlayerManager::OnClientPutInServer(IServerGameClients* clients, edict_t *pEntity, const char *playername)
{ {
cell_t res; cell_t res;
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
@ -693,21 +673,21 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
m_SourceTVUserId = userId; m_SourceTVUserId = userId;
} }
if (!OnClientConnect(pEntity, playername, "127.0.0.1", error, sizeof(error))) if (!OnClientConnect(clients, pEntity, playername, "127.0.0.1", error, sizeof(error)).ret)
{ {
/* :TODO: kick the bot if it's rejected */ /* :TODO: kick the bot if it's rejected */
return; return { KHook::Action::Ignore };
} }
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnClientConnected(client); pListener->OnClientConnected(client);
/* See if bot was kicked */ /* See if bot was kicked */
if (!pPlayer->IsConnected()) if (!pPlayer->IsConnected())
{ {
return; return { KHook::Action::Ignore };
} }
} }
@ -720,7 +700,7 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
const char *steamId = pPlayer->GetSteam2Id(); const char *steamId = pPlayer->GetSteam2Id();
/* Now do authorization */ /* Now do authorization */
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnClientAuthorized(client, steamId ? steamId : pPlayer->m_AuthID.c_str()); pListener->OnClientAuthorized(client, steamId ? steamId : pPlayer->m_AuthID.c_str());
@ -751,9 +731,8 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
pPlayer->Connect(); pPlayer->Connect();
m_PlayerCount++; m_PlayerCount++;
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnClientPutInServer(client); pListener->OnClientPutInServer(client);
@ -766,6 +745,8 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
{ {
pPlayer->DoPostConnectAuthorization(); pPlayer->DoPostConnectAuthorization();
} }
return { KHook::Action::Ignore };
} }
void PlayerManager::OnSourceModLevelEnd() void PlayerManager::OnSourceModLevelEnd()
@ -775,14 +756,14 @@ void PlayerManager::OnSourceModLevelEnd()
{ {
if (m_Players[i].IsConnected()) if (m_Players[i].IsConnected())
{ {
OnClientDisconnect(m_Players[i].GetEdict()); OnClientDisconnect(serverClients, m_Players[i].GetEdict());
OnClientDisconnect_Post(m_Players[i].GetEdict()); OnClientDisconnect_Post(serverClients, m_Players[i].GetEdict());
} }
} }
m_PlayerCount = 0; m_PlayerCount = 0;
} }
void PlayerManager::OnServerHibernationUpdate(bool bHibernating) KHook::Return<void> PlayerManager::OnServerHibernationUpdate(IServerGameDLL*, bool bHibernating)
{ {
cell_t res; cell_t res;
if (bHibernating) if (bHibernating)
@ -805,14 +786,16 @@ void PlayerManager::OnServerHibernationUpdate(bool bHibernating)
if (pPlayer->IsSourceTV() || pPlayer->IsReplay()) if (pPlayer->IsSourceTV() || pPlayer->IsReplay())
continue; continue;
#endif #endif
OnClientDisconnect(m_Players[i].GetEdict()); OnClientDisconnect(serverClients, m_Players[i].GetEdict());
OnClientDisconnect_Post(m_Players[i].GetEdict()); OnClientDisconnect_Post(serverClients, m_Players[i].GetEdict());
} }
} }
} }
return { KHook::Action::Ignore };
} }
void PlayerManager::OnClientDisconnect(edict_t *pEntity) KHook::Return<void> PlayerManager::OnClientDisconnect(IServerGameClients*, edict_t *pEntity)
{ {
cell_t res; cell_t res;
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
@ -826,7 +809,7 @@ void PlayerManager::OnClientDisconnect(edict_t *pEntity)
else else
{ {
/* We don't care, prevent a double call */ /* We don't care, prevent a double call */
return; return { KHook::Action::Ignore };
} }
if (pPlayer->WasCountedAsInGame()) if (pPlayer->WasCountedAsInGame())
@ -834,23 +817,23 @@ void PlayerManager::OnClientDisconnect(edict_t *pEntity)
m_PlayerCount--; m_PlayerCount--;
} }
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnClientDisconnecting(client); pListener->OnClientDisconnecting(client);
} }
return { KHook::Action::Ignore };
} }
void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity) KHook::Return<void> PlayerManager::OnClientDisconnect_Post(IServerGameClients*, edict_t *pEntity)
{ {
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
CPlayer *pPlayer = &m_Players[client]; CPlayer *pPlayer = &m_Players[client];
if (!pPlayer->IsConnected()) if (!pPlayer->IsConnected())
{ {
/* We don't care, prevent a double call */ /* We don't care, prevent a double call */
return; return { KHook::Action::Ignore };
} }
InvalidatePlayer(pPlayer); InvalidatePlayer(pPlayer);
@ -865,26 +848,26 @@ void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity)
m_cldisconnect_post->PushCell(client); m_cldisconnect_post->PushCell(client);
m_cldisconnect_post->Execute(&res, NULL); m_cldisconnect_post->Execute(&res, NULL);
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnClientDisconnected(client); pListener->OnClientDisconnected(client);
} }
return { KHook::Action::Ignore };
} }
void PlayerManager::OnClientPrintf(edict_t *pEdict, const char *szMsg) KHook::Return<void> PlayerManager::OnClientPrintf(IVEngineServer*, edict_t *pEdict, const char *szMsg)
{ {
int client = IndexOfEdict(pEdict); int client = IndexOfEdict(pEdict);
CPlayer &player = m_Players[client]; CPlayer &player = m_Players[client];
if (!player.IsConnected()) if (!player.IsConnected())
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(client)); INetChannel *pNetChan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(client));
if (pNetChan == NULL) if (pNetChan == NULL)
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
size_t nMsgLen = strlen(szMsg); size_t nMsgLen = strlen(szMsg);
#if SOURCE_ENGINE == SE_EPISODEONE || SOURCE_ENGINE == SE_DARKMESSIAH #if SOURCE_ENGINE == SE_EPISODEONE || SOURCE_ENGINE == SE_DARKMESSIAH
@ -895,7 +878,7 @@ void PlayerManager::OnClientPrintf(edict_t *pEdict, const char *szMsg)
// if the msg is bigger than allowed then just let it fail // if the msg is bigger than allowed then just let it fail
if (nMsgLen + 1 >= SVC_Print_BufferSize) // +1 for NETMSG_TYPE_BITS if (nMsgLen + 1 >= SVC_Print_BufferSize) // +1 for NETMSG_TYPE_BITS
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
// enqueue msgs if we'd overflow the SVC_Print buffer (+7 as ceil) // enqueue msgs if we'd overflow the SVC_Print buffer (+7 as ceil)
if (!player.m_PrintfBuffer.empty() || (nNumBitsWritten + NETMSG_TYPE_BITS + 7) / 8 + nMsgLen >= SVC_Print_BufferSize) if (!player.m_PrintfBuffer.empty() || (nNumBitsWritten + NETMSG_TYPE_BITS + 7) / 8 + nMsgLen >= SVC_Print_BufferSize)
@ -907,10 +890,10 @@ void PlayerManager::OnClientPrintf(edict_t *pEdict, const char *szMsg)
player.m_PrintfBuffer.push_back(szMsg); player.m_PrintfBuffer.push_back(szMsg);
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
} }
void PlayerManager::OnPrintfFrameAction(unsigned int serial) void PlayerManager::OnPrintfFrameAction(unsigned int serial)
@ -944,7 +927,7 @@ void PlayerManager::OnPrintfFrameAction(unsigned int serial)
if ((nNumBitsWritten + NETMSG_TYPE_BITS + 7) / 8 + string.length() >= SVC_Print_BufferSize) if ((nNumBitsWritten + NETMSG_TYPE_BITS + 7) / 8 + string.length() >= SVC_Print_BufferSize)
break; break;
SH_CALL(engine, &IVEngineServer::ClientPrintf)(player.m_pEdict, string.c_str()); KHook::CallOriginal(&IVEngineServer::ClientPrintf, engine, player.m_pEdict, string.c_str());
player.m_PrintfBuffer.pop_front(); player.m_PrintfBuffer.pop_front();
} }
@ -1045,7 +1028,7 @@ void ListPluginsToClient(CPlayer *player, const CCommand &args)
return; return;
} }
SourceHook::List<SMPlugin *> m_FailList; std::list<SMPlugin *> m_FailList;
size_t i = 0; size_t i = 0;
for (; i < plugins->size(); i++) for (; i < plugins->size(); i++)
@ -1077,10 +1060,10 @@ void ListPluginsToClient(CPlayer *player, const CCommand &args)
} }
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void PlayerManager::OnClientCommand(edict_t *pEntity, const CCommand &args) KHook::Return<void> PlayerManager::OnClientCommand(IServerGameClients*, edict_t *pEntity, const CCommand &args)
{ {
#else #else
void PlayerManager::OnClientCommand(edict_t *pEntity) KHook::Return<void> PlayerManager::OnClientCommand(IServerGameClients*, edict_t *pEntity)
{ {
CCommand args; CCommand args;
#endif #endif
@ -1091,7 +1074,7 @@ void PlayerManager::OnClientCommand(edict_t *pEntity)
if (!pPlayer->IsConnected()) if (!pPlayer->IsConnected())
{ {
return; return { KHook::Action::Ignore };
} }
if (strcmp(args.Arg(0), "sm") == 0) if (strcmp(args.Arg(0), "sm") == 0)
@ -1099,12 +1082,12 @@ void PlayerManager::OnClientCommand(edict_t *pEntity)
if (args.ArgC() > 1 && strcmp(args.Arg(1), "plugins") == 0) if (args.ArgC() > 1 && strcmp(args.Arg(1), "plugins") == 0)
{ {
ListPluginsToClient(pPlayer, args); ListPluginsToClient(pPlayer, args);
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
else if (args.ArgC() > 1 && strcmp(args.Arg(1), "exts") == 0) else if (args.ArgC() > 1 && strcmp(args.Arg(1), "exts") == 0)
{ {
ListExtensionsToClient(pPlayer, args); ListExtensionsToClient(pPlayer, args);
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
else if (args.ArgC() > 1 && strcmp(args.Arg(1), "credits") == 0) else if (args.ArgC() > 1 && strcmp(args.Arg(1), "credits") == 0)
{ {
@ -1124,7 +1107,7 @@ void PlayerManager::OnClientCommand(edict_t *pEntity)
" Borja \"faluco\" Ferrer, Pavol \"PM OnoTo\" Marko"); " Borja \"faluco\" Ferrer, Pavol \"PM OnoTo\" Marko");
ClientConsolePrint(pEntity, ClientConsolePrint(pEntity,
"SourceMod is open source under the GNU General Public License."); "SourceMod is open source under the GNU General Public License.");
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
ClientConsolePrint(pEntity, ClientConsolePrint(pEntity,
@ -1135,7 +1118,7 @@ void PlayerManager::OnClientCommand(edict_t *pEntity)
"To see credits, type \"sm credits\""); "To see credits, type \"sm credits\"");
ClientConsolePrint(pEntity, ClientConsolePrint(pEntity,
"Visit https://www.sourcemod.net/"); "Visit https://www.sourcemod.net/");
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
EngineArgs cargs(args); EngineArgs cargs(args);
@ -1161,7 +1144,7 @@ void PlayerManager::OnClientCommand(edict_t *pEntity)
cell_t res2 = g_ConsoleDetours.InternalDispatch(client, &cargs); cell_t res2 = g_ConsoleDetours.InternalDispatch(client, &cargs);
if (res2 >= Pl_Handled) if (res2 >= Pl_Handled)
{ {
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
else if (res2 > res) else if (res2 > res)
{ {
@ -1184,21 +1167,22 @@ void PlayerManager::OnClientCommand(edict_t *pEntity)
if (res >= Pl_Stop) if (res >= Pl_Stop)
{ {
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
res = g_ConCmds.DispatchClientCommand(client, cmd, argcount, (ResultType)res); res = g_ConCmds.DispatchClientCommand(client, cmd, argcount, (ResultType)res);
if (res >= Pl_Handled) if (res >= Pl_Handled)
{ {
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
return { KHook::Action::Ignore };
} }
#if SOURCE_ENGINE >= SE_EYE #if SOURCE_ENGINE >= SE_EYE
static bool s_LastCCKVAllowed = true; static bool s_LastCCKVAllowed = true;
void PlayerManager::OnClientCommandKeyValues(edict_t *pEntity, KeyValues *pCommand) KHook::Return<void> PlayerManager::OnClientCommandKeyValues(IServerGameClients*, edict_t *pEntity, KeyValues *pCommand)
{ {
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
@ -1207,12 +1191,12 @@ void PlayerManager::OnClientCommandKeyValues(edict_t *pEntity, KeyValues *pComma
if (!pPlayer->IsInGame()) if (!pPlayer->IsInGame())
{ {
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
} }
KeyValueStack *pStk = new KeyValueStack; KeyValueStack *pStk = new KeyValueStack;
pStk->pBase = pCommand; pStk->pBase = pCommand;
pStk->pCurRoot.push(pStk->pBase); pStk->pCurRoot.push_front(pStk->pBase);
pStk->m_bDeleteOnDestroy = false; pStk->m_bDeleteOnDestroy = false;
Handle_t hndl = handlesys->CreateHandle(g_KeyValueType, pStk, g_pCoreIdent, g_pCoreIdent, NULL); Handle_t hndl = handlesys->CreateHandle(g_KeyValueType, pStk, g_pCoreIdent, g_pCoreIdent, NULL);
@ -1231,19 +1215,19 @@ void PlayerManager::OnClientCommandKeyValues(edict_t *pEntity, KeyValues *pComma
if (res >= Pl_Handled) if (res >= Pl_Handled)
{ {
s_LastCCKVAllowed = false; s_LastCCKVAllowed = false;
RETURN_META(MRES_SUPERCEDE); return { KHook::Action::Supersede };
} }
s_LastCCKVAllowed = true; s_LastCCKVAllowed = true;
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
} }
void PlayerManager::OnClientCommandKeyValues_Post(edict_t *pEntity, KeyValues *pCommand) KHook::Return<void> PlayerManager::OnClientCommandKeyValues_Post(IServerGameClients*, edict_t *pEntity, KeyValues *pCommand)
{ {
if (!s_LastCCKVAllowed) if (!s_LastCCKVAllowed)
{ {
return; return { KHook::Action::Ignore };
} }
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
@ -1252,12 +1236,12 @@ void PlayerManager::OnClientCommandKeyValues_Post(edict_t *pEntity, KeyValues *p
if (!pPlayer->IsInGame()) if (!pPlayer->IsInGame())
{ {
return; return { KHook::Action::Ignore };
} }
KeyValueStack *pStk = new KeyValueStack; KeyValueStack *pStk = new KeyValueStack;
pStk->pBase = pCommand; pStk->pBase = pCommand;
pStk->pCurRoot.push(pStk->pBase); pStk->pCurRoot.push_front(pStk->pBase);
pStk->m_bDeleteOnDestroy = false; pStk->m_bDeleteOnDestroy = false;
Handle_t hndl = handlesys->CreateHandle(g_KeyValueType, pStk, g_pCoreIdent, g_pCoreIdent, NULL); Handle_t hndl = handlesys->CreateHandle(g_KeyValueType, pStk, g_pCoreIdent, g_pCoreIdent, NULL);
@ -1272,10 +1256,12 @@ void PlayerManager::OnClientCommandKeyValues_Post(edict_t *pEntity, KeyValues *p
// Deletes pStk // Deletes pStk
handlesys->FreeHandle(hndl, &sec); handlesys->FreeHandle(hndl, &sec);
return { KHook::Action::Ignore };
} }
#endif #endif
void PlayerManager::OnClientSettingsChanged(edict_t *pEntity) KHook::Return<void> PlayerManager::OnClientSettingsChanged(IServerGameClients*, edict_t *pEntity)
{ {
cell_t res; cell_t res;
int client = IndexOfEdict(pEntity); int client = IndexOfEdict(pEntity);
@ -1283,7 +1269,7 @@ void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
if (!pPlayer->IsConnected()) if (!pPlayer->IsConnected())
{ {
return; return { KHook::Action::Ignore };
} }
m_clinfochanged->PushCell(client); m_clinfochanged->PushCell(client);
@ -1305,7 +1291,7 @@ void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
char kickMsg[128]; char kickMsg[128];
logicore.CoreTranslate(kickMsg, sizeof(kickMsg), "%T", 2, NULL, "Name Reserved", &client); logicore.CoreTranslate(kickMsg, sizeof(kickMsg), "%T", 2, NULL, "Name Reserved", &client);
pPlayer->Kick(kickMsg); pPlayer->Kick(kickMsg);
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
} }
} }
else if ((id = adminsys->FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) { else if ((id = adminsys->FindAdminByIdentity("name", old_name)) != INVALID_ADMIN_ID) {
@ -1347,15 +1333,14 @@ void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
new_name, pPlayer->GetUserId(), accountId & 1, accountId >> 1, networkid_force, pPlayer->GetIPAddress()); new_name, pPlayer->GetUserId(), accountId & 1, accountId >> 1, networkid_force, pPlayer->GetIPAddress());
pPlayer->Kick("NetworkID spoofing detected."); pPlayer->Kick("NetworkID spoofing detected.");
RETURN_META(MRES_IGNORED); return { KHook::Action::Ignore };
} }
#endif #endif
} }
/* Notify Extensions */ /* Notify Extensions */
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
if (pListener->GetClientListenerVersion() >= 13) if (pListener->GetClientListenerVersion() >= 13)
@ -1363,6 +1348,7 @@ void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
pListener->OnClientSettingsChanged(client); pListener->OnClientSettingsChanged(client);
} }
} }
return { KHook::Action::Ignore };
} }
void PlayerManager::OnClientLanguageChanged(int client, unsigned int language) void PlayerManager::OnClientLanguageChanged(int client, unsigned int language)
@ -1842,8 +1828,7 @@ void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
} }
} }
List<ICommandTargetProcessor *>::iterator iter; for (auto iter = target_processors.begin(); iter != target_processors.end(); iter++)
for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
{ {
ICommandTargetProcessor *pProcessor = (*iter); ICommandTargetProcessor *pProcessor = (*iter);
if (pProcessor->ProcessCommandTarget(info)) if (pProcessor->ProcessCommandTarget(info))
@ -1926,9 +1911,8 @@ void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
} }
/* Notify Extensions */ /* Notify Extensions */
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL; IClientListener *pListener = NULL;
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
if (pListener->GetClientListenerVersion() >= 8) if (pListener->GetClientListenerVersion() >= 8)
@ -1961,14 +1945,16 @@ int PlayerManager::GetClientFromSerial(unsigned int serial)
} }
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void CmdMaxplayersCallback(const CCommand &command) KHook::Return<void> CmdMaxplayersCallback(ConCommand*, const CCommand &command)
{ {
#else #else
void CmdMaxplayersCallback() KHook::Return<void> CmdMaxplayersCallback(ConCommand*)
{ {
#endif #endif
g_Players.MaxPlayersChanged(); g_Players.MaxPlayersChanged();
return { KHook::Action::Ignore };
} }
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
@ -2451,8 +2437,7 @@ void CPlayer::DoPostConnectAuthorization()
{ {
bool delay = false; bool delay = false;
List<IClientListener *>::iterator iter; for (auto iter = g_Players.m_hooks.begin();
for (iter = g_Players.m_hooks.begin();
iter != g_Players.m_hooks.end(); iter != g_Players.m_hooks.end();
iter++) iter++)
{ {
@ -2511,8 +2496,7 @@ void CPlayer::NotifyPostAdminChecks()
/* Block beforehand so they can't double-call */ /* Block beforehand so they can't double-call */
m_bAdminCheckSignalled = true; m_bAdminCheckSignalled = true;
List<IClientListener *>::iterator iter; for (auto iter = g_Players.m_hooks.begin();
for (iter = g_Players.m_hooks.begin();
iter != g_Players.m_hooks.end(); iter != g_Players.m_hooks.end();
iter++) iter++)
{ {

View File

@ -39,17 +39,15 @@
#include <IPlayerHelpers.h> #include <IPlayerHelpers.h>
#include <IAdminSystem.h> #include <IAdminSystem.h>
#include <ITranslator.h> #include <ITranslator.h>
#include <sh_string.h> #include <string>
#include <sh_list.h> #include <list>
#include <sh_vector.h> #include <vector>
#include <am-string.h> #include <am-string.h>
#include <am-deque.h> #include <am-deque.h>
#include "ConVarManager.h" #include "ConVarManager.h"
#include <steam/steamclientpublic.h> #include <steam/steamclientpublic.h>
using namespace SourceHook;
class IClient; class IClient;
#define PLAYER_LIFE_UNKNOWN 0 #define PLAYER_LIFE_UNKNOWN 0
@ -131,9 +129,9 @@ private:
bool m_IsInGame = false; bool m_IsInGame = false;
bool m_IsAuthorized = false; bool m_IsAuthorized = false;
bool m_bIsInKickQueue = false; bool m_bIsInKickQueue = false;
String m_Name; std::string m_Name;
String m_Ip; std::string m_Ip;
String m_IpNoPort; std::string m_IpNoPort;
std::string m_AuthID; std::string m_AuthID;
std::string m_Steam2Id; std::string m_Steam2Id;
std::string m_Steam3Id; std::string m_Steam3Id;
@ -142,7 +140,7 @@ private:
edict_t *m_pEdict = nullptr; edict_t *m_pEdict = nullptr;
IPlayerInfo *m_Info = nullptr; IPlayerInfo *m_Info = nullptr;
IClient *m_pIClient = nullptr; IClient *m_pIClient = nullptr;
String m_LastPassword; std::string m_LastPassword;
bool m_bAdminCheckSignalled = false; bool m_bAdminCheckSignalled = false;
int m_iIndex; int m_iIndex;
unsigned int m_LangId = SOURCEMOD_LANGUAGE_ENGLISH; unsigned int m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
@ -178,25 +176,40 @@ public:
CPlayer *GetPlayerByIndex(int client) const; CPlayer *GetPlayerByIndex(int client) const;
void RunAuthChecks(); void RunAuthChecks();
public: public:
bool OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen); KHook::Virtual<IServerGameClients, bool, edict_t*, const char*, const char*, char*, int> m_HookClientConnect;
bool OnClientConnect_Post(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen); KHook::Return<bool> OnClientConnect(IServerGameClients*, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen);
void OnClientPutInServer(edict_t *pEntity, char const *playername); KHook::Return<bool> OnClientConnect_Post(IServerGameClients*, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen);
void OnClientDisconnect(edict_t *pEntity); KHook::Virtual<IServerGameClients, void, edict_t*, const char*> m_HookClientPutInServer;
void OnClientDisconnect_Post(edict_t *pEntity); KHook::Return<void> OnClientPutInServer(IServerGameClients*, edict_t *pEntity, char const *playername);
KHook::Virtual<IServerGameClients, void, edict_t*> m_HookClientDisconnect;
KHook::Return<void> OnClientDisconnect(IServerGameClients*, edict_t *pEntity);
KHook::Return<void> OnClientDisconnect_Post(IServerGameClients*, edict_t *pEntity);
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void OnClientCommand(edict_t *pEntity, const CCommand &args); KHook::Virtual<IServerGameClients, void, edict_t*, const CCommand&> m_HookClientCommand;
KHook::Return<void> OnClientCommand(IServerGameClients*, edict_t *pEntity, const CCommand &args);
#if SOURCE_ENGINE >= SE_EYE #if SOURCE_ENGINE >= SE_EYE
void OnClientCommandKeyValues(edict_t *pEntity, KeyValues *pCommand); KHook::Virtual<IServerGameClients, void, edict_t*, KeyValues*> m_HookClientCommandKeyValues;
void OnClientCommandKeyValues_Post(edict_t *pEntity, KeyValues *pCommand); KHook::Return<void> OnClientCommandKeyValues(IServerGameClients*, edict_t *pEntity, KeyValues *pCommand);
KHook::Return<void> OnClientCommandKeyValues_Post(IServerGameClients*, edict_t *pEntity, KeyValues *pCommand);
#endif #endif
#else #else
void OnClientCommand(edict_t *pEntity); KHook::Virtual<IServerGameClients, void, edict_t*> m_HookClientCommand;
KHook::Return<void> OnClientCommand(IServerGameClients*, edict_t *pEntity);
#endif #endif
void OnClientSettingsChanged(edict_t *pEntity); KHook::Virtual<IServerGameClients, void, edict_t*> m_HookClientSettingsChanged;
KHook::Return<void> OnClientSettingsChanged(IServerGameClients*, edict_t *pEntity);
//void OnClientSettingsChanged_Pre(edict_t *pEntity); //void OnClientSettingsChanged_Pre(edict_t *pEntity);
void OnClientLanguageChanged(int client, unsigned int language); void OnClientLanguageChanged(int client, unsigned int language);
void OnServerHibernationUpdate(bool bHibernating); KHook::Virtual<IServerGameDLL, void, edict_t*, int, int> m_HookServerActivate;
void OnClientPrintf(edict_t *pEdict, const char *szMsg); KHook::Return<void> OnServerActivate(IServerGameDLL*, edict_t *pEdictList, int edictCount, int clientMax);
#if SOURCE_ENGINE >= SE_LEFT4DEAD
KHook::Virtual<IServerGameDLL, void, bool> m_HookOnServerHibernationUpdate;
#elif SOURCE_ENGINE > SE_EYE
KHook::Virtual<IServerGameDLL, void, bool> m_HookSetServerHibernation;
#endif
KHook::Return<void> OnServerHibernationUpdate(IServerGameDLL*, bool bHibernating);
KHook::Virtual<IVEngineServer, void, edict_t*, const char*> m_HookClientPrintf;
KHook::Return<void> OnClientPrintf(IVEngineServer*, edict_t *pEdict, const char *szMsg);
void OnPrintfFrameAction(unsigned int serial); void OnPrintfFrameAction(unsigned int serial);
public: //IPlayerManager public: //IPlayerManager
void AddClientListener(IClientListener *listener); void AddClientListener(IClientListener *listener);
@ -242,10 +255,9 @@ public:
bool HandleConVarQuery(QueryCvarCookie_t cookie, int client, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue); bool HandleConVarQuery(QueryCvarCookie_t cookie, int client, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue);
#endif #endif
private: private:
void OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax);
void InvalidatePlayer(CPlayer *pPlayer); void InvalidatePlayer(CPlayer *pPlayer);
private: private:
List<IClientListener *> m_hooks; std::list<IClientListener *> m_hooks;
IForward *m_clconnect; IForward *m_clconnect;
IForward *m_clconnect_post; IForward *m_clconnect_post;
IForward *m_cldisconnect; IForward *m_cldisconnect;
@ -266,7 +278,7 @@ private:
int m_PlayersSinceActive; int m_PlayersSinceActive;
bool m_bServerActivated; bool m_bServerActivated;
unsigned int *m_AuthQueue; unsigned int *m_AuthQueue;
String m_PassInfoVar; std::string m_PassInfoVar;
bool m_QueryLang; bool m_QueryLang;
bool m_bAuthstringValidation; // are we validating admins with steam before authorizing? bool m_bAuthstringValidation; // are we validating admins with steam before authorizing?
bool m_bIsListenServer; bool m_bIsListenServer;
@ -282,9 +294,9 @@ private:
}; };
#if SOURCE_ENGINE >= SE_ORANGEBOX #if SOURCE_ENGINE >= SE_ORANGEBOX
void CmdMaxplayersCallback(const CCommand &command); KHook::Return<void> CmdMaxplayersCallback(ConCommand*, const CCommand &command);
#else #else
void CmdMaxplayersCallback(); KHook::Return<void> CmdMaxplayersCallback(ConCommand*);
#endif #endif
extern void ClientConsolePrint(edict_t *e, const char *fmt, ...); extern void ClientConsolePrint(edict_t *e, const char *fmt, ...);

View File

@ -177,12 +177,11 @@ TimerSystem::TimerSystem()
TimerSystem::~TimerSystem() TimerSystem::~TimerSystem()
{ {
CStack<ITimer *>::iterator iter; while (!m_FreeTimers.empty())
for (iter=m_FreeTimers.begin(); iter!=m_FreeTimers.end(); iter++)
{ {
delete (*iter); delete m_FreeTimers.top();
m_FreeTimers.pop();
} }
m_FreeTimers.popall();
} }
void TimerSystem::OnSourceModAllInitialized() void TimerSystem::OnSourceModAllInitialized()
@ -304,7 +303,7 @@ ITimer *TimerSystem::CreateTimer(ITimedEvent *pCallbacks, float fInterval, void
{ {
pTimer = new ITimer; pTimer = new ITimer;
} else { } else {
pTimer = m_FreeTimers.front(); pTimer = m_FreeTimers.top();
m_FreeTimers.pop(); m_FreeTimers.pop();
} }
@ -402,7 +401,7 @@ void TimerSystem::KillTimer(ITimer *pTimer)
m_FreeTimers.push(pTimer); m_FreeTimers.push(pTimer);
} }
CStack<ITimer *> s_tokill; std::stack<ITimer *> s_tokill;
void TimerSystem::RemoveMapChangeTimers() void TimerSystem::RemoveMapChangeTimers()
{ {
ITimer *pTimer; ITimer *pTimer;
@ -428,7 +427,7 @@ void TimerSystem::RemoveMapChangeTimers()
while (!s_tokill.empty()) while (!s_tokill.empty())
{ {
KillTimer(s_tokill.front()); KillTimer(s_tokill.top());
s_tokill.pop(); s_tokill.pop();
} }
} }

View File

@ -33,16 +33,15 @@
#define _INCLUDE_SOURCEMOD_CTIMERSYS_H_ #define _INCLUDE_SOURCEMOD_CTIMERSYS_H_
#include <ITimerSystem.h> #include <ITimerSystem.h>
#include <sh_stack.h> #include <stack>
#include <sh_list.h> #include <list>
#include "sourcemm_api.h" #include "sourcemm_api.h"
#include "sm_globals.h" #include "sm_globals.h"
using namespace SourceHook;
using namespace SourceMod; using namespace SourceMod;
typedef List<ITimer *> TimerList; typedef std::list<ITimer *> TimerList;
typedef List<ITimer *>::iterator TimerIter; typedef TimerList::iterator TimerIter;
class SourceMod::ITimer class SourceMod::ITimer
{ {
@ -84,9 +83,9 @@ public:
void RemoveMapChangeTimers(); void RemoveMapChangeTimers();
void GameFrame(bool simulating); void GameFrame(bool simulating);
private: private:
List<ITimer *> m_SingleTimers; std::list<ITimer *> m_SingleTimers;
List<ITimer *> m_LoopTimers; std::list<ITimer *> m_LoopTimers;
CStack<ITimer *> m_FreeTimers; std::stack<ITimer *> m_FreeTimers;
IMapTimer *m_pMapTimer; IMapTimer *m_pMapTimer;
/* This is stuff for our manual ticking escapades. */ /* This is stuff for our manual ticking escapades. */

View File

@ -44,25 +44,19 @@
UserMessages g_UserMsgs; UserMessages g_UserMsgs;
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_DECL_HOOK3_void(IVEngineServer, SendUserMessage, SH_NOATTRIB, 0, IRecipientFilter &, int, const protobuf::Message &);
#else
#if SOURCE_ENGINE >= SE_LEFT4DEAD
SH_DECL_HOOK3(IVEngineServer, UserMessageBegin, SH_NOATTRIB, 0, bf_write *, IRecipientFilter *, int, const char *);
#else
SH_DECL_HOOK2(IVEngineServer, UserMessageBegin, SH_NOATTRIB, 0, bf_write *, IRecipientFilter *, int);
#endif
SH_DECL_HOOK0_void(IVEngineServer, MessageEnd, SH_NOATTRIB, 0);
#endif // ==SE_CSGO || ==SE_BLADE || ==SE_MCV
UserMessages::UserMessages() UserMessages::UserMessages()
#ifndef USE_PROTOBUF_USERMESSAGES #ifndef USE_PROTOBUF_USERMESSAGES
: m_InterceptBuffer(m_pBase, 2500) : m_InterceptBuffer(m_pBase, 2500),
{
#else #else
: m_InterceptBuffer(NULL) : m_InterceptBuffer(NULL),
{
#endif #endif
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
m_SendUserMessage(&IVEngineServer::SendUserMessage, this, &UserMessages::OnSendUserMessage_Pre, &UserMessages::OnSendUserMessage_Post)
#else
m_UserMessageBegin(&IVEngineServer::UserMessageBegin, this, &UserMessages::OnStartMessage_Pre, &UserMessages::OnStartMessage_Post),
m_MessageEnd(&IVEngineServer::MessageEnd, this, &UserMessages::OnMessageEnd_Pre, &UserMessages::OnMessageEnd_Post)
#endif
{
m_HookCount = 0; m_HookCount = 0;
m_InExec = false; m_InExec = false;
m_InHook = false; m_InHook = false;
@ -72,12 +66,11 @@ UserMessages::UserMessages()
UserMessages::~UserMessages() UserMessages::~UserMessages()
{ {
CStack<ListenerInfo *>::iterator iter; while (!m_FreeListeners.empty())
for (iter=m_FreeListeners.begin(); iter!=m_FreeListeners.end(); iter++)
{ {
delete (*iter); delete m_FreeListeners.top();
m_FreeListeners.pop();
} }
m_FreeListeners.popall();
} }
void UserMessages::OnSourceModStartup(bool late) void UserMessages::OnSourceModStartup(bool late)
@ -98,13 +91,10 @@ void UserMessages::OnSourceModAllShutdown()
if (m_HookCount) if (m_HookCount)
{ {
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Pre), false); m_SendUserMessage.Remove(engine);
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Post), true);
#else #else
SH_REMOVE_HOOK(IVEngineServer, UserMessageBegin, engine, SH_MEMBER(this, &UserMessages::OnStartMessage_Pre), false); m_UserMessageBegin.Remove(engine);
SH_REMOVE_HOOK(IVEngineServer, UserMessageBegin, engine, SH_MEMBER(this, &UserMessages::OnStartMessage_Post), true); m_MessageEnd.Remove(engine);
SH_REMOVE_HOOK(IVEngineServer, MessageEnd, engine, SH_MEMBER(this, &UserMessages::OnMessageEnd_Pre), false);
SH_REMOVE_HOOK(IVEngineServer, MessageEnd, engine, SH_MEMBER(this, &UserMessages::OnMessageEnd_Post), true);
#endif #endif
} }
m_HookCount = 0; m_HookCount = 0;
@ -218,9 +208,9 @@ bf_write *UserMessages::StartBitBufMessage(int msg_id, const cell_t players[], u
if (m_CurFlags & USERMSG_BLOCKHOOKS) if (m_CurFlags & USERMSG_BLOCKHOOKS)
{ {
#if SOURCE_ENGINE >= SE_LEFT4DEAD #if SOURCE_ENGINE >= SE_LEFT4DEAD
buffer = ENGINE_CALL(UserMessageBegin)(static_cast<IRecipientFilter *>(&m_CellRecFilter), msg_id, g_SMAPI->GetUserMessage(msg_id)); buffer = m_UserMessageBegin.CallOriginal(engine, static_cast<IRecipientFilter *>(&m_CellRecFilter), msg_id, g_SMAPI->GetUserMessage(msg_id));
#else #else
buffer = ENGINE_CALL(UserMessageBegin)(static_cast<IRecipientFilter *>(&m_CellRecFilter), msg_id); buffer = m_UserMessageBegin.CallOriginal(engine, static_cast<IRecipientFilter *>(&m_CellRecFilter), msg_id);
#endif #endif
} else { } else {
#if SOURCE_ENGINE >= SE_LEFT4DEAD #if SOURCE_ENGINE >= SE_LEFT4DEAD
@ -335,7 +325,7 @@ bool UserMessages::EndMessage()
#else #else
if (m_CurFlags & USERMSG_BLOCKHOOKS) if (m_CurFlags & USERMSG_BLOCKHOOKS)
{ {
ENGINE_CALL(MessageEnd)(); m_MessageEnd.CallOriginal(engine);
} else { } else {
engine->MessageEnd(); engine->MessageEnd();
} }
@ -413,7 +403,7 @@ bool UserMessages::InternalHook(int msg_id, IBitBufUserMessageListener *pListene
{ {
pInfo = new ListenerInfo; pInfo = new ListenerInfo;
} else { } else {
pInfo = m_FreeListeners.front(); pInfo = m_FreeListeners.top();
m_FreeListeners.pop(); m_FreeListeners.pop();
} }
@ -425,13 +415,10 @@ bool UserMessages::InternalHook(int msg_id, IBitBufUserMessageListener *pListene
if (!m_HookCount++) if (!m_HookCount++)
{ {
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_ADD_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Pre), false); m_SendUserMessage.Add(engine);
SH_ADD_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Post), true);
#else #else
SH_ADD_HOOK(IVEngineServer, UserMessageBegin, engine, SH_MEMBER(this, &UserMessages::OnStartMessage_Pre), false); m_UserMessageBegin.Add(engine);
SH_ADD_HOOK(IVEngineServer, UserMessageBegin, engine, SH_MEMBER(this, &UserMessages::OnStartMessage_Post), true); m_MessageEnd.Add(engine);
SH_ADD_HOOK(IVEngineServer, MessageEnd, engine, SH_MEMBER(this, &UserMessages::OnMessageEnd_Pre), false);
SH_ADD_HOOK(IVEngineServer, MessageEnd, engine, SH_MEMBER(this, &UserMessages::OnMessageEnd_Post), true);
#endif #endif
} }
@ -504,13 +491,10 @@ void UserMessages::_DecRefCounter()
if (--m_HookCount == 0) if (--m_HookCount == 0)
{ {
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Pre), false); m_SendUserMessage.Add(engine);
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Post), true);
#else #else
SH_REMOVE_HOOK(IVEngineServer, UserMessageBegin, engine, SH_MEMBER(this, &UserMessages::OnStartMessage_Pre), false); m_UserMessageBegin.Remove(engine);
SH_REMOVE_HOOK(IVEngineServer, UserMessageBegin, engine, SH_MEMBER(this, &UserMessages::OnStartMessage_Post), true); m_MessageEnd.Remove(engine);
SH_REMOVE_HOOK(IVEngineServer, MessageEnd, engine, SH_MEMBER(this, &UserMessages::OnMessageEnd_Pre), false);
SH_REMOVE_HOOK(IVEngineServer, MessageEnd, engine, SH_MEMBER(this, &UserMessages::OnMessageEnd_Post), true);
#endif #endif
} }
} }
@ -566,18 +550,18 @@ void UserMessages::OnSendUserMessage_Post(IRecipientFilter &filter, int msg_type
return; return;
#else #else
#define UM_RETURN_META_VALUE(res, val) \ #define UM_RETURN_META_VALUE(res, val) \
RETURN_META_VALUE(res, val) return { res, val };
#define UM_RETURN_META(res) \ #define UM_RETURN_META(res) \
RETURN_META(res) return { res };
#endif #endif
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
protobuf::Message *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_type, const char *msg_name) KHook::Return<protobuf::Message*> UserMessages::OnStartMessage_Pre(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name)
#elif SOURCE_ENGINE >= SE_LEFT4DEAD #elif SOURCE_ENGINE >= SE_LEFT4DEAD
bf_write *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_type, const char *msg_name) KHook::Return<bf_write*> UserMessages::OnStartMessage_Pre(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name)
#else #else
bf_write *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_type) KHook::Return<bf_write*> UserMessages::OnStartMessage_Pre(IVEngineServer*, IRecipientFilter *filter, int msg_type)
#endif #endif
{ {
bool is_intercept_empty = m_msgIntercepts[msg_type].empty(); bool is_intercept_empty = m_msgIntercepts[msg_type].empty();
@ -587,7 +571,7 @@ bf_write *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_typ
|| (m_InExec && (m_CurFlags & USERMSG_BLOCKHOOKS))) || (m_InExec && (m_CurFlags & USERMSG_BLOCKHOOKS)))
{ {
m_InHook = false; m_InHook = false;
UM_RETURN_META_VALUE(MRES_IGNORED, NULL); UM_RETURN_META_VALUE(KHook::Action::Ignore, NULL)
} }
m_CurId = msg_type; m_CurId = msg_type;
@ -602,27 +586,28 @@ bf_write *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_typ
delete m_InterceptBuffer; delete m_InterceptBuffer;
m_InterceptBuffer = GetMessagePrototype(msg_type)->New(); m_InterceptBuffer = GetMessagePrototype(msg_type)->New();
UM_RETURN_META_VALUE(MRES_SUPERCEDE, m_InterceptBuffer); UM_RETURN_META_VALUE(KHook::Action::Supersede, m_InterceptBuffer)
#else #else
m_InterceptBuffer.Reset(); m_InterceptBuffer.Reset();
UM_RETURN_META_VALUE(MRES_SUPERCEDE, &m_InterceptBuffer);
UM_RETURN_META_VALUE(KHook::Action::Supersede, &m_InterceptBuffer)
#endif #endif
} }
UM_RETURN_META_VALUE(MRES_IGNORED, NULL); UM_RETURN_META_VALUE(KHook::Action::Ignore, NULL)
} }
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
protobuf::Message *UserMessages::OnStartMessage_Post(IRecipientFilter *filter, int msg_type, const char *msg_name) KHook::Return<protobuf::Message*> UserMessages::OnStartMessage_Post(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name)
#elif SOURCE_ENGINE >= SE_LEFT4DEAD #elif SOURCE_ENGINE >= SE_LEFT4DEAD
bf_write *UserMessages::OnStartMessage_Post(IRecipientFilter *filter, int msg_type, const char *msg_name) KHook::Return<bf_write*> UserMessages::OnStartMessage_Post(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name)
#else #else
bf_write *UserMessages::OnStartMessage_Post(IRecipientFilter *filter, int msg_type) KHook::Return<bf_write*> UserMessages::OnStartMessage_Post(IVEngineServer*, IRecipientFilter *filter, int msg_type)
#endif #endif
{ {
if (!m_InHook) if (!m_InHook)
{ {
UM_RETURN_META_VALUE(MRES_IGNORED, NULL); UM_RETURN_META_VALUE(KHook::Action::Ignore, NULL)
} }
#ifdef USE_PROTOBUF_USERMESSAGES #ifdef USE_PROTOBUF_USERMESSAGES
@ -631,17 +616,17 @@ bf_write *UserMessages::OnStartMessage_Post(IRecipientFilter *filter, int msg_ty
else else
m_OrigBuffer = m_FakeEngineBuffer; m_OrigBuffer = m_FakeEngineBuffer;
#else #else
m_OrigBuffer = META_RESULT_ORIG_RET(bf_write *); m_OrigBuffer = *(bf_write**)KHook::GetOriginalValuePtr();
#endif #endif
UM_RETURN_META_VALUE(MRES_IGNORED, NULL); UM_RETURN_META_VALUE(KHook::Action::Ignore, NULL)
} }
void UserMessages::OnMessageEnd_Post() KHook::Return<void> UserMessages::OnMessageEnd_Post(IVEngineServer*)
{ {
if (!m_InHook) if (!m_InHook)
{ {
UM_RETURN_META(MRES_IGNORED); UM_RETURN_META(KHook::Action::Ignore)
} }
MsgList *pList; MsgList *pList;
@ -703,13 +688,15 @@ void UserMessages::OnMessageEnd_Post()
pInfo->IsHooked = false; pInfo->IsHooked = false;
iter++; iter++;
} }
UM_RETURN_META(KHook::Action::Ignore)
} }
void UserMessages::OnMessageEnd_Pre() KHook::Return<void> UserMessages::OnMessageEnd_Pre(IVEngineServer*)
{ {
if (!m_InHook) if (!m_InHook)
{ {
UM_RETURN_META(MRES_IGNORED); UM_RETURN_META(KHook::Action::Ignore);
} }
MsgList *pList; MsgList *pList;
@ -778,17 +765,17 @@ void UserMessages::OnMessageEnd_Pre()
if (!handled && intercepted) if (!handled && intercepted)
{ {
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
ENGINE_CALL(SendUserMessage)(static_cast<IRecipientFilter &>(*m_CurRecFilter), m_CurId, *m_InterceptBuffer); m_SendUserMessage.CallOriginal(engine, static_cast<IRecipientFilter &>(*m_CurRecFilter), m_CurId, *m_InterceptBuffer);
#else #else
bf_write *engine_bfw; bf_write *engine_bfw;
#if SOURCE_ENGINE >= SE_LEFT4DEAD #if SOURCE_ENGINE >= SE_LEFT4DEAD
engine_bfw = ENGINE_CALL(UserMessageBegin)(m_CurRecFilter, m_CurId, g_SMAPI->GetUserMessage(m_CurId)); engine_bfw = m_UserMessageBegin.CallOriginal(engine, m_CurRecFilter, m_CurId, g_SMAPI->GetUserMessage(m_CurId));
#else #else
engine_bfw = ENGINE_CALL(UserMessageBegin)(m_CurRecFilter, m_CurId); engine_bfw = m_UserMessageBegin.CallOriginal(engine, m_CurRecFilter, m_CurId);
#endif #endif
m_ReadBuffer.StartReading(m_InterceptBuffer.GetBasePointer(), m_InterceptBuffer.GetNumBytesWritten()); m_ReadBuffer.StartReading(m_InterceptBuffer.GetBasePointer(), m_InterceptBuffer.GetNumBytesWritten());
engine_bfw->WriteBitsFromBuffer(&m_ReadBuffer, m_InterceptBuffer.GetNumBitsWritten()); engine_bfw->WriteBitsFromBuffer(&m_ReadBuffer, m_InterceptBuffer.GetNumBitsWritten());
ENGINE_CALL(MessageEnd)(); m_MessageEnd.CallOriginal(engine);
#endif // SE_CSGO || SE_BLADE || SE_MCV #endif // SE_CSGO || SE_BLADE || SE_MCV
} }
@ -828,8 +815,8 @@ void UserMessages::OnMessageEnd_Pre()
#endif #endif
} }
UM_RETURN_META((intercepted) ? MRES_SUPERCEDE : MRES_IGNORED); UM_RETURN_META((intercepted) ? KHook::Action::Supersede : KHook::Action::Ignore);
supercede: supercede:
m_BlockEndPost = true; m_BlockEndPost = true;
UM_RETURN_META(MRES_SUPERCEDE); UM_RETURN_META(KHook::Action::Supersede)
} }

View File

@ -38,10 +38,9 @@
#include "sm_stringutil.h" #include "sm_stringutil.h"
#include "CellRecipientFilter.h" #include "CellRecipientFilter.h"
#include "sm_globals.h" #include "sm_globals.h"
#include <sh_list.h> #include <list>
#include <sh_stack.h> #include <stack>
using namespace SourceHook;
using namespace SourceMod; using namespace SourceMod;
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
@ -72,8 +71,8 @@ struct ListenerInfo
bool IsNew; bool IsNew;
}; };
typedef List<ListenerInfo *> MsgList; typedef std::list<ListenerInfo *> MsgList;
typedef List<ListenerInfo *>::iterator MsgIter; typedef MsgList::iterator MsgIter;
class UserMessages : class UserMessages :
public IUserMessages, public IUserMessages,
@ -103,22 +102,22 @@ public: //IUserMessages
UserMessageType GetUserMessageType() const; UserMessageType GetUserMessageType() const;
public: public:
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
void OnSendUserMessage_Pre(IRecipientFilter &filter, int msg_type, const protobuf::Message &msg); KHook::Return<void> OnSendUserMessage_Pre(IVEngineServer*, IRecipientFilter &filter, int msg_type, const protobuf::Message &msg);
void OnSendUserMessage_Post(IRecipientFilter &filter, int msg_type, const protobuf::Message &msg); KHook::Return<void> OnSendUserMessage_Post(IVEngineServer*, IRecipientFilter &filter, int msg_type, const protobuf::Message &msg);
#endif #endif
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
protobuf::Message *OnStartMessage_Pre(IRecipientFilter *filter, int msg_type, const char *msg_name); KHook::Return<protobuf::Message*> OnStartMessage_Pre(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name);
protobuf::Message *OnStartMessage_Post(IRecipientFilter *filter, int msg_type, const char *msg_name); KHook::Return<protobuf::Message*> OnStartMessage_Post(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name);
#elif SOURCE_ENGINE >= SE_LEFT4DEAD #elif SOURCE_ENGINE >= SE_LEFT4DEAD
bf_write *OnStartMessage_Pre(IRecipientFilter *filter, int msg_type, const char *msg_name); KHook::Return<bf_write*> OnStartMessage_Pre(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name);
bf_write *OnStartMessage_Post(IRecipientFilter *filter, int msg_type, const char *msg_name); KHook::Return<bf_write*> OnStartMessage_Post(IVEngineServer*, IRecipientFilter *filter, int msg_type, const char *msg_name);
#else #else
bf_write *OnStartMessage_Pre(IRecipientFilter *filter, int msg_type); KHook::Return<bf_write*> OnStartMessage_Pre(IVEngineServer*, IRecipientFilter *filter, int msg_type);
bf_write *OnStartMessage_Post(IRecipientFilter *filter, int msg_type); KHook::Return<bf_write*> OnStartMessage_Post(IVEngineServer*, IRecipientFilter *filter, int msg_type);
#endif #endif
void OnMessageEnd_Pre(); KHook::Return<void> OnMessageEnd_Pre(IVEngineServer*);
void OnMessageEnd_Post(); KHook::Return<void> OnMessageEnd_Post(IVEngineServer*);
private: private:
#ifdef USE_PROTOBUF_USERMESSAGES #ifdef USE_PROTOBUF_USERMESSAGES
const protobuf::Message *GetMessagePrototype(int msg_type); const protobuf::Message *GetMessagePrototype(int msg_type);
@ -130,9 +129,9 @@ private:
#endif #endif
void _DecRefCounter(); void _DecRefCounter();
private: private:
List<ListenerInfo *> m_msgHooks[255]; std::list<ListenerInfo *> m_msgHooks[255];
List<ListenerInfo *> m_msgIntercepts[255]; std::list<ListenerInfo *> m_msgIntercepts[255];
CStack<ListenerInfo *> m_FreeListeners; std::stack<ListenerInfo *> m_FreeListeners;
IRecipientFilter *m_CurRecFilter; IRecipientFilter *m_CurRecFilter;
#ifndef USE_PROTOBUF_USERMESSAGES #ifndef USE_PROTOBUF_USERMESSAGES
unsigned char m_pBase[2500]; unsigned char m_pBase[2500];
@ -159,6 +158,17 @@ private:
bool m_InExec; bool m_InExec;
int m_CurFlags; int m_CurFlags;
int m_CurId; int m_CurId;
protected:
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
KHook::Virtual<IVEngineServer, void, IRecipientFilter&, int, const protobuf::Message&> m_SendUserMessage;
#else
#if SOURCE_ENGINE >= SE_LEFT4DEAD
KHook::Virtual<IVEngineServer, bf_write*, IRecipientFilter*, int, const char*> m_UserMessageBegin;
#else
KHook::Virtual<IVEngineServer, bf_write*, IRecipientFilter*, int> m_UserMessageBegin;
#endif
KHook::Virtual<IVEngineServer, void> m_MessageEnd;
#endif // ==SE_CSGO || ==SE_BLADE || ==SE_MCV
}; };
extern UserMessages g_UserMsgs; extern UserMessages g_UserMsgs;

View File

@ -26,7 +26,7 @@
// or <http://www.sourcemod.net/license.php>. // or <http://www.sourcemod.net/license.php>.
#include "sm_globals.h" #include "sm_globals.h"
#include <sh_list.h> #include <list>
#include <convar.h> #include <convar.h>
#include "concmd_cleaner.h" #include "concmd_cleaner.h"
#include "sm_stringutil.h" #include "sm_stringutil.h"
@ -34,19 +34,6 @@
#include "compat_wrappers.h" #include "compat_wrappers.h"
#include <amtl/am-string.h> #include <amtl/am-string.h>
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_HOOK1_void(ICvar, UnregisterConCommand, SH_NOATTRIB, 0, ConCommandBase *);
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_DECL_HOOK2_void(ICvar, RegisterConCommand, SH_NOATTRIB, 0, ConCommandBase *, bool);
#else
SH_DECL_HOOK1_void(ICvar, RegisterConCommand, SH_NOATTRIB, 0, ConCommandBase *);
#endif
#else
SH_DECL_HOOK1_void(ICvar, RegisterConCommandBase, SH_NOATTRIB, 0, ConCommandBase *);
#endif
using namespace SourceHook;
struct ConCommandInfo struct ConCommandInfo
{ {
ConCommandBase *pBase; ConCommandBase *pBase;
@ -54,7 +41,7 @@ struct ConCommandInfo
char name[64]; char name[64];
}; };
List<ConCommandInfo *> tracked_bases; std::list<ConCommandInfo *> tracked_bases;
IConCommandLinkListener *IConCommandLinkListener::head = NULL; IConCommandLinkListener *IConCommandLinkListener::head = NULL;
ConCommandBase *FindConCommandBase(const char *name); ConCommandBase *FindConCommandBase(const char *name);
@ -62,30 +49,12 @@ ConCommandBase *FindConCommandBase(const char *name);
class ConCommandCleaner : public SMGlobalClass class ConCommandCleaner : public SMGlobalClass
{ {
public: public:
void OnSourceModAllInitialized()
{
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_ADD_HOOK(ICvar, UnregisterConCommand, icvar, SH_MEMBER(this, &ConCommandCleaner::UnlinkConCommandBase), false);
SH_ADD_HOOK(ICvar, RegisterConCommand, icvar, SH_MEMBER(this, &ConCommandCleaner::LinkConCommandBase), false);
#else
SH_ADD_HOOK(ICvar, RegisterConCommandBase, icvar, SH_MEMBER(this, &ConCommandCleaner::LinkConCommandBase), false);
#endif
}
void OnSourceModShutdown()
{
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_REMOVE_HOOK(ICvar, UnregisterConCommand, icvar, SH_MEMBER(this, &ConCommandCleaner::UnlinkConCommandBase), false);
SH_REMOVE_HOOK(ICvar, RegisterConCommand, icvar, SH_MEMBER(this, &ConCommandCleaner::LinkConCommandBase), false);
#else
SH_REMOVE_HOOK(ICvar, RegisterConCommandBase, icvar, SH_MEMBER(this, &ConCommandCleaner::LinkConCommandBase), false);
#endif
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
void LinkConCommandBase(ConCommandBase *pBase, bool unknown) KHook::Virtual<ICvar, void, ConCommandBase*, bool> m_HookLinkConCommandBase;
KHook::Return<void> LinkConCommandBase(ICvar*, ConCommandBase *pBase, bool unknown)
#else #else
void LinkConCommandBase(ConCommandBase *pBase) KHook::Virtual<ICvar, void, ConCommandBase*> m_HookLinkConCommandBase;
KHook::Return<void> LinkConCommandBase(ICvar*, ConCommandBase *pBase)
#endif #endif
{ {
IConCommandLinkListener *listener = IConCommandLinkListener::head; IConCommandLinkListener *listener = IConCommandLinkListener::head;
@ -94,12 +63,15 @@ public:
listener->OnLinkConCommand(pBase); listener->OnLinkConCommand(pBase);
listener = listener->next; listener = listener->next;
} }
return { KHook::Action::Ignore };
} }
void UnlinkConCommandBase(ConCommandBase *pBase) KHook::Virtual<ICvar, void, ConCommandBase*> m_HookUnlinkConCommandBase;
KHook::Return<void> UnlinkConCommandBase(ICvar*, ConCommandBase *pBase)
{ {
ConCommandInfo *pInfo; ConCommandInfo *pInfo;
List<ConCommandInfo *>::iterator iter = tracked_bases.begin(); auto iter = tracked_bases.begin();
IConCommandLinkListener *listener = IConCommandLinkListener::head; IConCommandLinkListener *listener = IConCommandLinkListener::head;
while (listener) while (listener)
@ -122,6 +94,7 @@ public:
iter++; iter++;
} }
} }
return { KHook::Action::Ignore };
} }
void AddTarget(ConCommandBase *pBase, IConCommandTracker *cls) void AddTarget(ConCommandBase *pBase, IConCommandTracker *cls)
@ -137,10 +110,9 @@ public:
void RemoveTarget(ConCommandBase *pBase, IConCommandTracker *cls) void RemoveTarget(ConCommandBase *pBase, IConCommandTracker *cls)
{ {
List<ConCommandInfo *>::iterator iter;
ConCommandInfo *pInfo; ConCommandInfo *pInfo;
iter = tracked_bases.begin(); auto iter = tracked_bases.begin();
while (iter != tracked_bases.end()) while (iter != tracked_bases.end())
{ {
pInfo = (*iter); pInfo = (*iter);
@ -155,6 +127,35 @@ public:
} }
} }
} }
virtual void OnSourceModAllInitialized() override
{
#if SOURCE_ENGINE >= SE_ORANGEBOX
m_HookUnlinkConCommandBase.Add(icvar);
m_HookLinkConCommandBase.Add(icvar);
#else
m_HookLinkConCommandBase.Add(icvar);
#endif
}
virtual void OnSourceModShutdown() override
{
#if SOURCE_ENGINE >= SE_ORANGEBOX
m_HookUnlinkConCommandBase.Remove(icvar);
m_HookLinkConCommandBase.Remove(icvar);
#else
m_HookLinkConCommandBase.Remove(icvar);
#endif
}
ConCommandCleaner() :
#if SOURCE_ENGINE >= SE_ORANGEBOX
m_HookLinkConCommandBase(&ICvar::RegisterConCommand, this, &ConCommandCleaner::LinkConCommandBase, nullptr),
m_HookUnlinkConCommandBase(&ICvar::UnregisterConCommand, this, &ConCommandCleaner::UnlinkConCommandBase, nullptr)
#else
m_HookLinkConCommandBase(&ICvar::RegisterConCommandBase, this, &ConCommandCleaner::LinkConCommandBase, nullptr)
#endif
{}
} s_ConCmdTracker; } s_ConCmdTracker;
void TrackConCommandBase(ConCommandBase *pBase, IConCommandTracker *me) void TrackConCommandBase(ConCommandBase *pBase, IConCommandTracker *me)
@ -169,5 +170,5 @@ void UntrackConCommandBase(ConCommandBase *pBase, IConCommandTracker *me)
void Global_OnUnlinkConCommandBase(ConCommandBase *pBase) void Global_OnUnlinkConCommandBase(ConCommandBase *pBase)
{ {
s_ConCmdTracker.UnlinkConCommandBase(pBase); s_ConCmdTracker.UnlinkConCommandBase(icvar, pBase);
} }

View File

@ -10,7 +10,7 @@ for cxx in builder.targets:
os.path.join(builder.sourcePath, 'sourcepawn', 'include'), os.path.join(builder.sourcePath, 'sourcepawn', 'include'),
os.path.join(builder.sourcePath, 'public', 'amtl', 'amtl'), os.path.join(builder.sourcePath, 'public', 'amtl', 'amtl'),
os.path.join(builder.sourcePath, 'public', 'amtl'), os.path.join(builder.sourcePath, 'public', 'amtl'),
os.path.join(SM.mms_root, 'core', 'sourcehook') os.path.join(SM.mms_root, 'third_party', 'khook', 'include')
] ]
binary.compiler.defines += [ binary.compiler.defines += [
'SM_DEFAULT_THREADER', 'SM_DEFAULT_THREADER',

View File

@ -233,8 +233,7 @@ AdminCache::~AdminCache()
DumpAdminCache(AdminCache_Overrides, false); DumpAdminCache(AdminCache_Overrides, false);
DumpAdminCache(AdminCache_Groups, false); DumpAdminCache(AdminCache_Groups, false);
List<AuthMethod *>::iterator iter; for (auto iter=m_AuthMethods.begin();
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end(); iter!=m_AuthMethods.end();
iter++) iter++)
{ {
@ -759,8 +758,7 @@ bool AdminCache::GetGroupCommandOverride(GroupId id, const char *name, OverrideT
AuthMethod *AdminCache::GetMethodByIndex(unsigned int index) AuthMethod *AdminCache::GetMethodByIndex(unsigned int index)
{ {
List<AuthMethod *>::iterator iter; for (auto iter=m_AuthMethods.begin();
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end(); iter!=m_AuthMethods.end();
iter++) iter++)
{ {
@ -974,8 +972,7 @@ void AdminCache::InvalidateAdminCache(bool unlink_admins)
} }
} }
/* Wipe the identity cache first */ /* Wipe the identity cache first */
List<AuthMethod *>::iterator iter; for (auto iter=m_AuthMethods.begin();
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end(); iter!=m_AuthMethods.end();
iter++) iter++)
{ {
@ -998,7 +995,6 @@ void AdminCache::InvalidateAdminCache(bool unlink_admins)
void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild) void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
{ {
List<IAdminListener *>::iterator iter;
IAdminListener *pListener; IAdminListener *pListener;
if (part == AdminCache_Overrides) if (part == AdminCache_Overrides)
@ -1007,7 +1003,7 @@ void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
DumpCommandOverrideCache(Override_CommandGroup); DumpCommandOverrideCache(Override_CommandGroup);
if (rebuild && !m_destroying) if (rebuild && !m_destroying)
{ {
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnRebuildOverrideCache(); pListener->OnRebuildOverrideCache();
@ -1021,7 +1017,7 @@ void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
InvalidateGroupCache(); InvalidateGroupCache();
if (rebuild && !m_destroying) if (rebuild && !m_destroying)
{ {
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnRebuildGroupCache(); pListener->OnRebuildGroupCache();
@ -1033,7 +1029,7 @@ void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
InvalidateAdminCache(true); InvalidateAdminCache(true);
if (rebuild && !m_destroying) if (rebuild && !m_destroying)
{ {
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{ {
pListener = (*iter); pListener = (*iter);
pListener->OnRebuildAdminCache((part == AdminCache_Groups)); pListener->OnRebuildAdminCache((part == AdminCache_Groups));
@ -1058,9 +1054,8 @@ const char *AdminCache::GetAdminName(AdminId id)
bool AdminCache::GetMethodIndex(const char *name, unsigned int *_index) bool AdminCache::GetMethodIndex(const char *name, unsigned int *_index)
{ {
List<AuthMethod *>::iterator iter;
unsigned int index = 0; unsigned int index = 0;
for (iter=m_AuthMethods.begin(); for (auto iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end(); iter!=m_AuthMethods.end();
iter++,index++) iter++,index++)
{ {
@ -1962,8 +1957,7 @@ AdminUser *AdminCache::GetUser(AdminId aid)
const char *AdminCache::GetMethodName(unsigned int index) const char *AdminCache::GetMethodName(unsigned int index)
{ {
List<AuthMethod *>::iterator iter; for (auto iter=m_AuthMethods.begin();
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end(); iter!=m_AuthMethods.end();
iter++) iter++)
{ {

View File

@ -33,16 +33,12 @@
#define _INCLUDE_SOURCEMOD_ADMINCACHE_H_ #define _INCLUDE_SOURCEMOD_ADMINCACHE_H_
#include "common_logic.h" #include "common_logic.h"
#include <IAdminSystem.h> #include "sm_hashmap.h"
#include "sm_memtable.h" #include "sm_memtable.h"
#include <sm_trie.h> #include "sm_namehashset.h"
#include <sh_list.h> #include <IAdminSystem.h>
#include <sh_string.h>
#include <IForwardSys.h> #include <IForwardSys.h>
#include <sm_hashmap.h> #include <list>
#include <sm_namehashset.h>
using namespace SourceHook;
#define GRP_MAGIC_SET 0xDEADFADE #define GRP_MAGIC_SET 0xDEADFADE
#define GRP_MAGIC_UNSET 0xFACEFACE #define GRP_MAGIC_UNSET 0xFACEFACE
@ -70,7 +66,7 @@ struct AdminGroup
struct AuthMethod struct AuthMethod
{ {
String name; std::string name;
StringHashMap<AdminId> identities; StringHashMap<AdminId> identities;
AuthMethod(const char *name) AuthMethod(const char *name)
@ -214,8 +210,8 @@ public:
int m_LastGroup; int m_LastGroup;
int m_FreeGroupList; int m_FreeGroupList;
StringHashMap<GroupId> m_Groups; StringHashMap<GroupId> m_Groups;
List<IAdminListener *> m_hooks; std::list<IAdminListener *> m_hooks;
List<AuthMethod *> m_AuthMethods; std::list<AuthMethod *> m_AuthMethods;
NameHashSet<AuthMethod *> m_AuthTables; NameHashSet<AuthMethod *> m_AuthTables;
IForward *m_pCacheFwd; IForward *m_pCacheFwd;
int m_FirstUser; int m_FirstUser;

View File

@ -109,10 +109,9 @@ SWThreadHandle *BaseWorker::PopThreadFromQueue()
if (!m_ThreadQueue.size()) if (!m_ThreadQueue.size())
return NULL; return NULL;
SourceHook::List<SWThreadHandle *>::iterator begin;
SWThreadHandle *swt; SWThreadHandle *swt;
begin = m_ThreadQueue.begin(); auto begin = m_ThreadQueue.begin();
swt = (*begin); swt = (*begin);
m_ThreadQueue.erase(begin); m_ThreadQueue.erase(begin);

View File

@ -32,7 +32,7 @@
#ifndef _INCLUDE_SOURCEMOD_BASEWORKER_H #ifndef _INCLUDE_SOURCEMOD_BASEWORKER_H
#define _INCLUDE_SOURCEMOD_BASEWORKER_H #define _INCLUDE_SOURCEMOD_BASEWORKER_H
#include "sh_list.h" #include <list>
#include "ThreadSupport.h" #include "ThreadSupport.h"
#define SM_DEFAULT_THREADS_PER_FRAME 1 #define SM_DEFAULT_THREADS_PER_FRAME 1
@ -96,7 +96,7 @@ public: //BaseWorker
virtual void AddThreadToQueue(SWThreadHandle *pHandle); virtual void AddThreadToQueue(SWThreadHandle *pHandle);
virtual SWThreadHandle *PopThreadFromQueue(); virtual SWThreadHandle *PopThreadFromQueue();
protected: protected:
SourceHook::List<SWThreadHandle *> m_ThreadQueue; std::list<SWThreadHandle *> m_ThreadQueue;
unsigned int m_perFrame; unsigned int m_perFrame;
volatile WorkerState m_state; volatile WorkerState m_state;
IThreadWorkerCallbacks *m_pHooks; IThreadWorkerCallbacks *m_pHooks;

View File

@ -204,7 +204,7 @@ void DBManager::RemoveDriver(IDBDriver *pDriver)
{ {
if (m_drivers[i] == pDriver) if (m_drivers[i] == pDriver)
{ {
m_drivers.erase(m_drivers.iterAt(i)); m_drivers.erase(m_drivers.begin() + i);
break; break;
} }
} }

View File

@ -33,9 +33,9 @@
#define _INCLUDE_DATABASE_MANAGER_H_ #define _INCLUDE_DATABASE_MANAGER_H_
#include "common_logic.h" #include "common_logic.h"
#include <sh_vector.h> #include <vector>
#include <am-string.h> #include <am-string.h>
#include <sh_list.h> #include <list>
#include <IThreader.h> #include <IThreader.h>
#include <IPluginSys.h> #include <IPluginSys.h>
#include <condition_variable> #include <condition_variable>
@ -46,8 +46,6 @@
#include <am-refcounting.h> #include <am-refcounting.h>
#include "DatabaseConfBuilder.h" #include "DatabaseConfBuilder.h"
using namespace SourceHook;
class DBManager : class DBManager :
public IDBManager, public IDBManager,
@ -98,12 +96,12 @@ private:
void ClearConfigs(); void ClearConfigs();
void KillWorkerThread(); void KillWorkerThread();
private: private:
CVector<IDBDriver *> m_drivers; std::vector<IDBDriver *> m_drivers;
/* Threading stuff */ /* Threading stuff */
PrioQueue<IDBThreadOperation *> m_OpQueue; PrioQueue<IDBThreadOperation *> m_OpQueue;
Queue<IDBThreadOperation *> m_ThinkQueue; Queue<IDBThreadOperation *> m_ThinkQueue;
CVector<bool> m_drSafety; /* which drivers are safe? */ std::vector<bool> m_drSafety; /* which drivers are safe? */
std::unique_ptr<std::thread> m_Worker; std::unique_ptr<std::thread> m_Worker;
std::condition_variable m_QueueEvent; std::condition_variable m_QueueEvent;
std::mutex m_ThinkLock; std::mutex m_ThinkLock;

View File

@ -346,7 +346,15 @@ void CExtension::MarkAllLoaded()
void CExtension::AddPlugin(CPlugin *pPlugin) void CExtension::AddPlugin(CPlugin *pPlugin)
{ {
/* Unfortunately we have to do this :( */ /* Unfortunately we have to do this :( */
if (m_Dependents.find(pPlugin) == m_Dependents.end()) auto iter = m_Dependents.begin();
while (iter != m_Dependents.end()) {
if ((*iter) == pPlugin) {
break;
} else {
iter++;
}
}
if (iter == m_Dependents.end())
{ {
m_Dependents.push_back(pPlugin); m_Dependents.push_back(pPlugin);
} }
@ -389,7 +397,12 @@ bool CLocalExtension::IsLoaded()
void CExtension::AddDependency(const IfaceInfo *pInfo) void CExtension::AddDependency(const IfaceInfo *pInfo)
{ {
if (m_Deps.find(*pInfo) == m_Deps.end()) auto iter = m_Deps.begin();
while (iter != m_Deps.end() && !((*iter) == (*pInfo)))
{
iter++;
}
if (iter == m_Deps.end())
{ {
m_Deps.push_back(*pInfo); m_Deps.push_back(*pInfo);
} }
@ -401,8 +414,7 @@ void CExtension::AddChildDependent(CExtension *pOther, SMInterface *iface)
info.iface = iface; info.iface = iface;
info.owner = pOther; info.owner = pOther;
List<IfaceInfo>::iterator iter; for (auto iter = m_ChildDeps.begin();
for (iter = m_ChildDeps.begin();
iter != m_ChildDeps.end(); iter != m_ChildDeps.end();
iter++) iter++)
{ {
@ -482,7 +494,7 @@ void CExtensionManager::OnSourceModShutdown()
void CExtensionManager::Shutdown() void CExtensionManager::Shutdown()
{ {
List<CExtension *>::iterator iter; auto iter = m_Libs.begin();
while ((iter = m_Libs.begin()) != m_Libs.end()) while ((iter = m_Libs.begin()) != m_Libs.end())
{ {
@ -575,14 +587,13 @@ IExtension *CExtensionManager::LoadAutoExtension(const char *path, bool bErrorOn
IExtension *CExtensionManager::FindExtensionByFile(const char *file) IExtension *CExtensionManager::FindExtensionByFile(const char *file)
{ {
List<CExtension *>::iterator iter;
CExtension *pExt; CExtension *pExt;
/* Chomp off the path */ /* Chomp off the path */
char lookup[PLATFORM_MAX_PATH]; char lookup[PLATFORM_MAX_PATH];
libsys->GetFileFromPath(lookup, sizeof(lookup), file); libsys->GetFileFromPath(lookup, sizeof(lookup), file);
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++) for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{ {
pExt = (*iter); pExt = (*iter);
if (pExt->IsSameFile(lookup)) if (pExt->IsSameFile(lookup))
@ -596,12 +607,11 @@ IExtension *CExtensionManager::FindExtensionByFile(const char *file)
IExtension *CExtensionManager::FindExtensionByName(const char *ext) IExtension *CExtensionManager::FindExtensionByName(const char *ext)
{ {
List<CExtension *>::iterator iter;
CExtension *pExt; CExtension *pExt;
IExtensionInterface *pAPI; IExtensionInterface *pAPI;
const char *name; const char *name;
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++) for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{ {
pExt = (*iter); pExt = (*iter);
if (!pExt->IsLoaded()) if (!pExt->IsLoaded())
@ -710,9 +720,7 @@ void CExtensionManager::BindChildPlugin(IExtension *pParent, SMPlugin *pPlugin)
void CExtensionManager::OnPluginDestroyed(IPlugin *plugin) void CExtensionManager::OnPluginDestroyed(IPlugin *plugin)
{ {
List<CExtension *>::iterator iter; for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{ {
(*iter)->DropRefsTo(static_cast<CPlugin *>(plugin)); (*iter)->DropRefsTo(static_cast<CPlugin *>(plugin));
} }
@ -725,7 +733,7 @@ CExtension *CExtensionManager::FindByOrder(unsigned int num)
return NULL; return NULL;
} }
List<CExtension *>::iterator iter = m_Libs.begin(); auto iter = m_Libs.begin();
while (iter != m_Libs.end()) while (iter != m_Libs.end())
{ {
@ -745,8 +753,12 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
return false; return false;
CExtension *pExt = (CExtension *)_pExt; CExtension *pExt = (CExtension *)_pExt;
auto iter = m_Libs.begin();
if (m_Libs.find(pExt) == m_Libs.end()) while (iter != m_Libs.end() && (*iter) != pExt)
{
iter++;
}
if (iter == m_Libs.end())
return false; return false;
/* Tell it to unload */ /* Tell it to unload */
@ -760,13 +772,13 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
g_ShareSys.RemoveInterfaces(_pExt); g_ShareSys.RemoveInterfaces(_pExt);
m_Libs.remove(pExt); m_Libs.remove(pExt);
List<CExtension *> UnloadQueue; std::list<CExtension *> UnloadQueue;
/* Handle dependencies */ /* Handle dependencies */
if (pExt->IsLoaded()) if (pExt->IsLoaded())
{ {
/* Unload any dependent plugins */ /* Unload any dependent plugins */
List<CPlugin *>::iterator p_iter = pExt->m_Dependents.begin(); auto p_iter = pExt->m_Dependents.begin();
while (p_iter != pExt->m_Dependents.end()) while (p_iter != pExt->m_Dependents.end())
{ {
/* We have to manually unlink ourselves here, since we're no longer being managed */ /* We have to manually unlink ourselves here, since we're no longer being managed */
@ -774,8 +786,7 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
p_iter = pExt->m_Dependents.erase(p_iter); p_iter = pExt->m_Dependents.erase(p_iter);
} }
List<String>::iterator s_iter; for (auto s_iter = pExt->m_Libraries.begin();
for (s_iter = pExt->m_Libraries.begin();
s_iter != pExt->m_Libraries.end(); s_iter != pExt->m_Libraries.end();
s_iter++) s_iter++)
{ {
@ -783,10 +794,9 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
} }
/* Notify and/or unload all dependencies */ /* Notify and/or unload all dependencies */
List<CExtension *>::iterator c_iter;
CExtension *pDep; CExtension *pDep;
IExtensionInterface *pAPI; IExtensionInterface *pAPI;
for (c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++) for (auto c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
{ {
pDep = (*c_iter); pDep = (*c_iter);
if ((pAPI=pDep->GetAPI()) == NULL) if ((pAPI=pDep->GetAPI()) == NULL)
@ -795,7 +805,7 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
continue; continue;
/* Now, get its dependency list */ /* Now, get its dependency list */
bool dropped = false; bool dropped = false;
List<IfaceInfo>::iterator i_iter = pDep->m_Deps.begin(); auto i_iter = pDep->m_Deps.begin();
while (i_iter != pDep->m_Deps.end()) while (i_iter != pDep->m_Deps.end())
{ {
if ((*i_iter).owner == _pExt) if ((*i_iter).owner == _pExt)
@ -850,8 +860,7 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
pExt->Unload(); pExt->Unload();
delete pExt; delete pExt;
List<CExtension *>::iterator iter; for (auto iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
for (iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
{ {
/* NOTE: This is safe because the unload function backs out of anything not present */ /* NOTE: This is safe because the unload function backs out of anything not present */
UnloadExtension((*iter)); UnloadExtension((*iter));
@ -862,10 +871,9 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
void CExtensionManager::MarkAllLoaded() void CExtensionManager::MarkAllLoaded()
{ {
List<CExtension *>::iterator iter;
CExtension *pExt; CExtension *pExt;
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++) for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{ {
pExt = (*iter); pExt = (*iter);
if (!pExt->IsLoaded()) if (!pExt->IsLoaded())
@ -900,7 +908,6 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
const char *cmd = command->Arg(2); const char *cmd = command->Arg(2);
if (strcmp(cmd, "list") == 0) if (strcmp(cmd, "list") == 0)
{ {
List<CExtension *>::iterator iter;
CExtension *pExt; CExtension *pExt;
unsigned int num = 1; unsigned int num = 1;
@ -922,7 +929,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
break; break;
} }
} }
for (iter = m_Libs.begin(); iter != m_Libs.end(); iter++,num++) for (auto iter = m_Libs.begin(); iter != m_Libs.end(); iter++,num++)
{ {
pExt = (*iter); pExt = (*iter);
if (pExt->IsLoaded()) if (pExt->IsLoaded())
@ -1011,7 +1018,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
return; return;
} }
List<CExtension *>::iterator iter = m_Libs.begin(); auto iter = m_Libs.begin();
CExtension *pExt = NULL; CExtension *pExt = NULL;
while (iter != m_Libs.end()) while (iter != m_Libs.end())
{ {
@ -1114,23 +1121,21 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
} }
else else
{ {
List<CPlugin *> plugins; std::list<CPlugin *> plugins;
if (pExt->m_ChildDeps.size()) if (pExt->m_ChildDeps.size())
{ {
rootmenu->ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename()); rootmenu->ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename());
List<CExtension *>::iterator iter;
CExtension *pOther; CExtension *pOther;
/* Get list of all extensions */ /* Get list of all extensions */
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++) for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{ {
List<IfaceInfo>::iterator i_iter;
pOther = (*iter); pOther = (*iter);
if (!pOther->IsLoaded() || pOther == pExt) if (!pOther->IsLoaded() || pOther == pExt)
{ {
continue; continue;
} }
/* Get their dependencies */ /* Get their dependencies */
for (i_iter=pOther->m_Deps.begin(); for (auto i_iter=pOther->m_Deps.begin();
i_iter!=pOther->m_Deps.end(); i_iter!=pOther->m_Deps.end();
i_iter++) i_iter++)
{ {
@ -1144,12 +1149,16 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
{ {
rootmenu->ConsolePrint(" -> %s", pOther->GetFilename()); rootmenu->ConsolePrint(" -> %s", pOther->GetFilename());
/* Add to plugin unload list */ /* Add to plugin unload list */
List<CPlugin *>::iterator p_iter; for (auto p_iter=pOther->m_Dependents.begin();
for (p_iter=pOther->m_Dependents.begin();
p_iter!=pOther->m_Dependents.end(); p_iter!=pOther->m_Dependents.end();
p_iter++) p_iter++)
{ {
if (plugins.find((*p_iter)) == plugins.end()) auto iterS = plugins.begin();
while (iterS != plugins.end() && (*iterS) != (*p_iter))
{
iterS++;
}
if (iterS == plugins.end())
{ {
plugins.push_back((*p_iter)); plugins.push_back((*p_iter));
} }
@ -1161,17 +1170,21 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
if (pExt->m_Dependents.size()) if (pExt->m_Dependents.size())
{ {
rootmenu->ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename()); rootmenu->ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename());
List<CPlugin *>::iterator iter;
CPlugin *pPlugin; CPlugin *pPlugin;
for (iter = pExt->m_Dependents.begin(); iter != pExt->m_Dependents.end(); iter++) for (auto iter = pExt->m_Dependents.begin(); iter != pExt->m_Dependents.end(); iter++)
{ {
pPlugin = (*iter); pPlugin = (*iter);
if (plugins.find(pPlugin) == plugins.end()) auto iterS = plugins.begin();
while (iterS != plugins.end() && (*iterS) != (pPlugin))
{
iterS++;
}
if (iterS == plugins.end())
{ {
plugins.push_back(pPlugin); plugins.push_back(pPlugin);
} }
} }
for (iter = plugins.begin(); iter != plugins.end(); iter++) for (auto iter = plugins.begin(); iter != plugins.end(); iter++)
{ {
pPlugin = (*iter); pPlugin = (*iter);
rootmenu->ConsolePrint(" -> %s", pPlugin->GetFilename()); rootmenu->ConsolePrint(" -> %s", pPlugin->GetFilename());
@ -1267,12 +1280,12 @@ bool CExtensionManager::LibraryExists(const char *library)
{ {
CExtension *pExt; CExtension *pExt;
for (List<CExtension *>::iterator iter = m_Libs.begin(); for (auto iter = m_Libs.begin();
iter != m_Libs.end(); iter != m_Libs.end();
iter++) iter++)
{ {
pExt = (*iter); pExt = (*iter);
for (List<String>::iterator s_iter = pExt->m_Libraries.begin(); for (auto s_iter = pExt->m_Libraries.begin();
s_iter != pExt->m_Libraries.end(); s_iter != pExt->m_Libraries.end();
s_iter++) s_iter++)
{ {
@ -1315,9 +1328,8 @@ IExtension *CExtensionManager::LoadExternal(IExtensionInterface *pInterface,
void CExtensionManager::CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax) void CExtensionManager::CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax)
{ {
IExtensionInterface *pAPI; IExtensionInterface *pAPI;
List<CExtension *>::iterator iter;
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++) for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{ {
if ((pAPI = (*iter)->GetAPI()) == NULL) if ((pAPI = (*iter)->GetAPI()) == NULL)
{ {
@ -1333,9 +1345,8 @@ void CExtensionManager::CallOnCoreMapStart(edict_t *pEdictList, int edictCount,
void CExtensionManager::CallOnCoreMapEnd() void CExtensionManager::CallOnCoreMapEnd()
{ {
IExtensionInterface *pAPI; IExtensionInterface *pAPI;
List<CExtension *>::iterator iter;
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++) for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{ {
if ((pAPI = (*iter)->GetAPI()) == NULL) if ((pAPI = (*iter)->GetAPI()) == NULL)
{ {
@ -1348,17 +1359,17 @@ void CExtensionManager::CallOnCoreMapEnd()
} }
} }
const CVector<IExtension *> *CExtensionManager::ListExtensions() const std::vector<IExtension *> *CExtensionManager::ListExtensions()
{ {
CVector<IExtension *> *list = new CVector<IExtension *>(); std::vector<IExtension *> *list = new std::vector<IExtension *>();
for (List<CExtension *>::iterator iter = m_Libs.begin(); iter != m_Libs.end(); iter++) for (auto iter = m_Libs.begin(); iter != m_Libs.end(); iter++)
list->push_back(*iter); list->push_back(*iter);
return list; return list;
} }
void CExtensionManager::FreeExtensionList(const CVector<IExtension *> *list) void CExtensionManager::FreeExtensionList(const std::vector<IExtension *> *list)
{ {
delete const_cast<CVector<IExtension *> *>(list); delete const_cast<std::vector<IExtension *> *>(list);
} }
bool CLocalExtension::IsSameFile(const char *file) bool CLocalExtension::IsSameFile(const char *file)

View File

@ -34,8 +34,8 @@
#include <IExtensionSys.h> #include <IExtensionSys.h>
#include <ILibrarySys.h> #include <ILibrarySys.h>
#include <sh_list.h> #include <list>
#include <sh_string.h> #include <string>
#include "common_logic.h" #include "common_logic.h"
#include <IPluginSys.h> #include <IPluginSys.h>
#include <IRootConsoleMenu.h> #include <IRootConsoleMenu.h>
@ -46,7 +46,6 @@
class CPlayer; class CPlayer;
using namespace SourceMod; using namespace SourceMod;
using namespace SourceHook;
class CExtension; class CExtension;
@ -95,14 +94,14 @@ protected:
protected: protected:
IdentityToken_t *m_pIdentToken; IdentityToken_t *m_pIdentToken;
IExtensionInterface *m_pAPI; IExtensionInterface *m_pAPI;
String m_File; std::string m_File;
String m_RealFile; std::string m_RealFile;
String m_Path; std::string m_Path;
String m_Error; std::string m_Error;
List<IfaceInfo> m_Deps; /** Dependencies */ std::list<IfaceInfo> m_Deps; /** Dependencies */
List<IfaceInfo> m_ChildDeps; /** Children who might depend on us */ std::list<IfaceInfo> m_ChildDeps; /** Children who might depend on us */
List<SMInterface *> m_Interfaces; std::list<SMInterface *> m_Interfaces;
List<String> m_Libraries; std::list<std::string> m_Libraries;
unsigned int unload_code; unsigned int unload_code;
bool m_bFullyLoaded; bool m_bFullyLoaded;
bool m_bRequired; bool m_bRequired;
@ -178,8 +177,8 @@ public:
void CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax); void CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax);
void CallOnCoreMapEnd(); void CallOnCoreMapEnd();
void AddRawDependency(IExtension *ext, IdentityToken_t *other, void *iface); void AddRawDependency(IExtension *ext, IdentityToken_t *other, void *iface);
const CVector<IExtension *> *ListExtensions(); const std::vector<IExtension *> *ListExtensions();
void FreeExtensionList(const CVector<IExtension *> *list); void FreeExtensionList(const std::vector<IExtension *> *list);
public: public:
CExtension *GetExtensionFromIdent(IdentityToken_t *ptr); CExtension *GetExtensionFromIdent(IdentityToken_t *ptr);
void Shutdown(); void Shutdown();
@ -191,7 +190,7 @@ public:
private: private:
CExtension *FindByOrder(unsigned int num); CExtension *FindByOrder(unsigned int num);
private: private:
List<CExtension *> m_Libs; std::list<CExtension *> m_Libs;
}; };
extern CExtensionManager g_Extensions; extern CExtensionManager g_Extensions;

View File

@ -31,8 +31,8 @@
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include <sstream> #include <sstream>
#include <sh_list.h> #include <list>
#include <sh_string.h> #include <string>
#include "GameConfigs.h" #include "GameConfigs.h"
#include "stringutil.h" #include "stringutil.h"
#include <IGameHelpers.h> #include <IGameHelpers.h>
@ -53,8 +53,6 @@
#include <dlfcn.h> #include <dlfcn.h>
#endif #endif
using namespace SourceHook;
GameConfigManager g_GameConfigs; GameConfigManager g_GameConfigs;
IGameConfig *g_pGameConf = NULL; IGameConfig *g_pGameConf = NULL;
static char g_Game[256]; static char g_Game[256];
@ -791,7 +789,11 @@ public:
(!had_game && matched_engine) || (!had_game && matched_engine) ||
(matched_engine && matched_game)) (matched_engine && matched_game))
{ {
if (fileList->find(cur_file) == fileList->end()) auto iterS = fileList->begin();
while (iterS != fileList->end() && (*iterS) != cur_file) {
iterS++;
}
if (iterS == fileList->end())
{ {
fileList->push_back(cur_file); fileList->push_back(cur_file);
} }
@ -806,7 +808,7 @@ public:
return SMCResult_Continue; return SMCResult_Continue;
} }
public: public:
List<String> *fileList; std::list<std::string> *fileList;
unsigned int state; unsigned int state;
unsigned int ignoreLevel; unsigned int ignoreLevel;
char cur_file[PLATFORM_MAX_PATH]; char cur_file[PLATFORM_MAX_PATH];
@ -857,7 +859,7 @@ bool CGameConfig::Reparse(char *error, size_t maxlength)
/* Otherwise, it's time to parse the master. */ /* Otherwise, it's time to parse the master. */
SMCError err; SMCError err;
SMCStates state = {0, 0}; SMCStates state = {0, 0};
List<String> fileList; std::list<std::string> fileList;
master_reader.fileList = &fileList; master_reader.fileList = &fileList;
const char *pEngine[2] = { m_pBaseEngine, m_pEngine }; const char *pEngine[2] = { m_pBaseEngine, m_pEngine };
@ -885,8 +887,7 @@ bool CGameConfig::Reparse(char *error, size_t maxlength)
} }
/* Go through each file we found and parse it. */ /* Go through each file we found and parse it. */
List<String>::iterator iter; for (auto iter = fileList.begin(); iter != fileList.end(); iter++)
for (iter = fileList.begin(); iter != fileList.end(); iter++)
{ {
ke::SafeSprintf(path, sizeof(path), "%s/%s", m_File, (*iter).c_str()); ke::SafeSprintf(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
if (!EnterFile(path, error, maxlength)) if (!EnterFile(path, error, maxlength))

View File

@ -35,10 +35,8 @@
#include <am-hashmap.h> #include <am-hashmap.h>
#include <memory> #include <memory>
#if defined PLATFORM_LINUX || defined PLATFORM_APPLE #if defined PLATFORM_LINUX || defined PLATFORM_APPLE
#include <sh_vector.h> #include <vector>
#include "sm_symtable.h" #include "sm_symtable.h"
using namespace SourceHook;
#endif #endif
using namespace SourceMod; using namespace SourceMod;
@ -79,7 +77,7 @@ public:
const DynLibInfo *GetLibraryInfo(const void *libPtr); const DynLibInfo *GetLibraryInfo(const void *libPtr);
#if defined PLATFORM_LINUX || defined PLATFORM_APPLE #if defined PLATFORM_LINUX || defined PLATFORM_APPLE
private: private:
CVector<LibSymbolTable *> m_SymTables; std::vector<LibSymbolTable *> m_SymTables;
#ifdef PLATFORM_APPLE #ifdef PLATFORM_APPLE
struct dyld_all_image_infos *m_ImageList; struct dyld_all_image_infos *m_ImageList;
SInt32 m_OSXMajor; SInt32 m_OSXMajor;

View File

@ -48,8 +48,17 @@ unsigned int CNativeOwner::GetMarkSerial()
void CNativeOwner::AddDependent(CPlugin *pPlugin) void CNativeOwner::AddDependent(CPlugin *pPlugin)
{ {
if (m_Dependents.find(pPlugin) == m_Dependents.end()) auto iter = m_Dependents.begin();
while (iter != m_Dependents.end()) {
if ((*iter) == pPlugin) {
break;
} else {
iter++;
}
}
if (iter == m_Dependents.end()) {
m_Dependents.push_back(pPlugin); m_Dependents.push_back(pPlugin);
}
} }
void CNativeOwner::AddWeakRef(const WeakNative & ref) void CNativeOwner::AddWeakRef(const WeakNative & ref)
@ -79,10 +88,8 @@ void CNativeOwner::UnbindWeakRef(const WeakNative &ref)
void CNativeOwner::DropEverything() void CNativeOwner::DropEverything()
{ {
List<WeakNative>::iterator iter;
/* Unbind and remove all weak references to us */ /* Unbind and remove all weak references to us */
iter = m_WeakRefs.begin(); auto iter = m_WeakRefs.begin();
while (iter != m_WeakRefs.end()) while (iter != m_WeakRefs.end())
{ {
UnbindWeakRef((*iter)); UnbindWeakRef((*iter));
@ -104,9 +111,7 @@ void CNativeOwner::DropEverything()
void CNativeOwner::DropWeakRefsTo(CPlugin *pPlugin) void CNativeOwner::DropWeakRefsTo(CPlugin *pPlugin)
{ {
List<WeakNative>::iterator iter; auto iter = m_WeakRefs.begin();
iter = m_WeakRefs.begin();
while (iter != m_WeakRefs.end()) while (iter != m_WeakRefs.end())
{ {
WeakNative & ref = (*iter); WeakNative & ref = (*iter);

View File

@ -32,7 +32,7 @@
#define _INCLUDE_SOURCEMOD_NATIVE_OWNER_H_ #define _INCLUDE_SOURCEMOD_NATIVE_OWNER_H_
#include <sp_vm_types.h> #include <sp_vm_types.h>
#include <sh_list.h> #include <list>
#include <am-vector.h> #include <am-vector.h>
#include "common_logic.h" #include "common_logic.h"
#include "Native.h" #include "Native.h"
@ -55,8 +55,6 @@ struct WeakNative
uint32_t idx; uint32_t idx;
}; };
using namespace SourceHook;
class CNativeOwner class CNativeOwner
{ {
public: public:
@ -76,9 +74,9 @@ private:
void DropWeakRefsTo(CPlugin *pPlugin); void DropWeakRefsTo(CPlugin *pPlugin);
void UnbindWeakRef(const WeakNative & ref); void UnbindWeakRef(const WeakNative & ref);
protected: protected:
List<CPlugin *> m_Dependents; std::list<CPlugin *> m_Dependents;
unsigned int m_nMarkSerial; unsigned int m_nMarkSerial;
List<WeakNative> m_WeakRefs; std::list<WeakNative> m_WeakRefs;
std::vector<const sp_nativeinfo_t *> m_natives; std::vector<const sp_nativeinfo_t *> m_natives;
std::vector<ke::RefPtr<Native> > m_fakes; std::vector<ke::RefPtr<Native> > m_fakes;
}; };

View File

@ -32,11 +32,9 @@
#ifndef _INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_ #ifndef _INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_
#define _INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_ #define _INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_
#include <string.h> #include <vector>
#include <sh_vector.h>
#include <ITranslator.h> #include <ITranslator.h>
using namespace SourceHook;
using namespace SourceMod; using namespace SourceMod;
class CPhraseCollection : public IPhraseCollection class CPhraseCollection : public IPhraseCollection
@ -60,7 +58,7 @@ public:
size_t *pOutLength, size_t *pOutLength,
const char **pFailPhrase); const char **pFailPhrase);
private: private:
CVector<IPhraseFile *> m_Files; std::vector<IPhraseFile *> m_Files;
}; };
#endif //_INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_ #endif //_INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_

View File

@ -668,7 +668,11 @@ void CPlugin::DependencyDropped(CPlugin *pOwner)
return; return;
for (auto lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++) { for (auto lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++) {
if (m_RequiredLibs.find(*lib_iter) != m_RequiredLibs.end()) { auto iterS = m_RequiredLibs.begin();
while (iterS != m_RequiredLibs.end() && (*iterS) != *lib_iter) {
iterS++;
}
if (iterS != m_RequiredLibs.end()) {
m_LibraryMissing = true; m_LibraryMissing = true;
break; break;
} }
@ -739,10 +743,9 @@ void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
void CPlugin::DropEverything() void CPlugin::DropEverything()
{ {
CPlugin *pOther; CPlugin *pOther;
List<WeakNative>::iterator wk_iter;
/* Tell everyone that depends on us that we're about to drop */ /* Tell everyone that depends on us that we're about to drop */
for (List<CPlugin *>::iterator iter = m_Dependents.begin(); for (auto iter = m_Dependents.begin();
iter != m_Dependents.end(); iter != m_Dependents.end();
iter++) iter++)
{ {
@ -1184,7 +1187,11 @@ void CPlugin::ForEachLibrary(ke::Function<void(const char *)> callback)
void CPlugin::AddRequiredLib(const char *name) void CPlugin::AddRequiredLib(const char *name)
{ {
if (m_RequiredLibs.find(name) == m_RequiredLibs.end()) auto iterS = m_RequiredLibs.begin();
while (iterS != m_RequiredLibs.end() && (*iterS) != name) {
iterS++;
}
if (iterS == m_RequiredLibs.end())
m_RequiredLibs.push_back(name); m_RequiredLibs.push_back(name);
} }
@ -2274,9 +2281,9 @@ void CPluginManager::SyncMaxClients(int max_clients)
(*iter)->SyncMaxClients(max_clients); (*iter)->SyncMaxClients(max_clients);
} }
const CVector<SMPlugin *> *CPluginManager::ListPlugins() const std::vector<SMPlugin *> *CPluginManager::ListPlugins()
{ {
CVector<SMPlugin *> *list = new CVector<SMPlugin *>(); std::vector<SMPlugin *> *list = new std::vector<SMPlugin *>();
for (PluginIter iter(m_plugins); !iter.done(); iter.next()) for (PluginIter iter(m_plugins); !iter.done(); iter.next())
list->push_back((*iter)); list->push_back((*iter));
@ -2284,9 +2291,9 @@ const CVector<SMPlugin *> *CPluginManager::ListPlugins()
return list; return list;
} }
void CPluginManager::FreePluginList(const CVector<SMPlugin *> *list) void CPluginManager::FreePluginList(const std::vector<SMPlugin *> *list)
{ {
delete const_cast<CVector<SMPlugin *> *>(list); delete const_cast<std::vector<SMPlugin *> *>(list);
} }
void CPluginManager::ForEachPlugin(ke::Function<void(CPlugin *)> callback) void CPluginManager::ForEachPlugin(ke::Function<void(CPlugin *)> callback)

View File

@ -41,10 +41,10 @@
#include <IPluginSys.h> #include <IPluginSys.h>
#include <IHandleSys.h> #include <IHandleSys.h>
#include <IForwardSys.h> #include <IForwardSys.h>
#include <sh_list.h> #include <list>
#include <sh_stack.h> #include <stack>
#include <sh_vector.h> #include <vector>
#include <sh_string.h> #include <string>
#include "common_logic.h" #include "common_logic.h"
#include <IRootConsoleMenu.h> #include <IRootConsoleMenu.h>
#include <sm_hashmap.h> #include <sm_hashmap.h>
@ -61,8 +61,6 @@
class CPlayer; class CPlayer;
using namespace SourceHook;
enum LoadRes enum LoadRes
{ {
LoadRes_Successful, LoadRes_Successful,
@ -196,7 +194,15 @@ public:
m_Libraries.push_back(name); m_Libraries.push_back(name);
} }
inline bool HasLibrary(const char *name) { inline bool HasLibrary(const char *name) {
return m_Libraries.find(name) != m_Libraries.end(); auto iter = m_Libraries.begin();
while (iter != m_Libraries.end()) {
if (strcmp((*iter).c_str(), name) == 0) {
break;
} else {
iter++;
}
}
return iter != m_Libraries.end();
} }
void LibraryActions(LibraryAction action); void LibraryActions(LibraryAction action);
void SyncMaxClients(int max_clients); void SyncMaxClients(int max_clients);
@ -275,13 +281,13 @@ private:
IPluginContext *m_pContext; IPluginContext *m_pContext;
sp_pubvar_t *m_MaxClientsVar; sp_pubvar_t *m_MaxClientsVar;
StringHashMap<void *> m_Props; StringHashMap<void *> m_Props;
CVector<AutoConfig *> m_configs; std::vector<AutoConfig *> m_configs;
List<String> m_Libraries; std::list<std::string> m_Libraries;
bool m_bGotAllLoaded; bool m_bGotAllLoaded;
int m_FileVersion; int m_FileVersion;
// Information that survives past eviction. // Information that survives past eviction.
List<String> m_RequiredLibs; std::list<std::string> m_RequiredLibs;
IdentityToken_t *m_ident; IdentityToken_t *m_ident;
time_t m_LastFileModTime; time_t m_LastFileModTime;
Handle_t m_handle; Handle_t m_handle;
@ -355,8 +361,8 @@ public: //IScriptManager
SMPlugin *FindPluginByHandle(Handle_t hndl, HandleError *errp) { SMPlugin *FindPluginByHandle(Handle_t hndl, HandleError *errp) {
return static_cast<SMPlugin *>(PluginFromHandle(hndl, errp)); return static_cast<SMPlugin *>(PluginFromHandle(hndl, errp));
} }
const CVector<SMPlugin *> *ListPlugins(); const std::vector<SMPlugin *> *ListPlugins();
void FreePluginList(const CVector<SMPlugin *> *plugins); void FreePluginList(const std::vector<SMPlugin *> *plugins);
public: //SMGlobalClass public: //SMGlobalClass
void OnSourceModAllInitialized(); void OnSourceModAllInitialized();
@ -513,7 +519,7 @@ private:
IdentityToken_t *m_MyIdent; IdentityToken_t *m_MyIdent;
/* Dynamic native stuff */ /* Dynamic native stuff */
List<FakeNative *> m_Natives; std::list<FakeNative *> m_Natives;
bool m_LoadingLocked; bool m_LoadingLocked;

View File

@ -42,8 +42,7 @@ RootConsoleMenu::RootConsoleMenu()
RootConsoleMenu::~RootConsoleMenu() RootConsoleMenu::~RootConsoleMenu()
{ {
List<ConsoleEntry *>::iterator iter; for (auto iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
{ {
delete (*iter); delete (*iter);
} }
@ -100,7 +99,7 @@ bool RootConsoleMenu::AddRootConsoleCommand3(const char *cmd,
return false; return false;
/* Sort this into the menu */ /* Sort this into the menu */
List<ConsoleEntry *>::iterator iter = m_Menu.begin(); auto iter = m_Menu.begin();
ConsoleEntry *pEntry; ConsoleEntry *pEntry;
bool inserted = false; bool inserted = false;
while (iter != m_Menu.end()) while (iter != m_Menu.end())
@ -137,9 +136,8 @@ bool RootConsoleMenu::RemoveRootConsoleCommand(const char *cmd, IRootConsoleComm
{ {
m_Commands.remove(cmd); m_Commands.remove(cmd);
List<ConsoleEntry *>::iterator iter;
ConsoleEntry *pEntry; ConsoleEntry *pEntry;
for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) for (auto iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
{ {
pEntry = (*iter); pEntry = (*iter);
if (pEntry->command.compare(cmd) == 0) if (pEntry->command.compare(cmd) == 0)
@ -200,9 +198,8 @@ void RootConsoleMenu::GotRootCmd(const ICommandArgs *cmd)
ConsolePrint("SourceMod Menu:"); ConsolePrint("SourceMod Menu:");
ConsolePrint("Usage: sm <command> [arguments]"); ConsolePrint("Usage: sm <command> [arguments]");
List<ConsoleEntry *>::iterator iter;
ConsoleEntry *pEntry; ConsoleEntry *pEntry;
for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) for (auto iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
{ {
pEntry = (*iter); pEntry = (*iter);
DrawGenericOption(pEntry->command.c_str(), pEntry->description.c_str()); DrawGenericOption(pEntry->command.c_str(), pEntry->description.c_str());

View File

@ -28,18 +28,17 @@
#define _INCLUDE_SOURCEMOD_ROOT_CONSOLE_MENU_IMPL_H_ #define _INCLUDE_SOURCEMOD_ROOT_CONSOLE_MENU_IMPL_H_
#include "common_logic.h" #include "common_logic.h"
#include "sm_namehashset.h"
#include <IRootConsoleMenu.h> #include <IRootConsoleMenu.h>
#include <sh_list.h> #include <string>
#include <sh_string.h> #include <list>
#include <sm_namehashset.h>
using namespace SourceMod; using namespace SourceMod;
using namespace SourceHook;
struct ConsoleEntry struct ConsoleEntry
{ {
String command; std::string command;
String description; std::string description;
IRootConsoleCommand *cmd; IRootConsoleCommand *cmd;
static inline bool matches(const char *name, const ConsoleEntry *entry) static inline bool matches(const char *name, const ConsoleEntry *entry)
@ -84,7 +83,7 @@ public:
void GotRootCmd(const ICommandArgs *cmd); void GotRootCmd(const ICommandArgs *cmd);
private: private:
NameHashSet<ConsoleEntry *> m_Commands; NameHashSet<ConsoleEntry *> m_Commands;
List<ConsoleEntry *> m_Menu; std::list<ConsoleEntry *> m_Menu;
}; };
extern RootConsoleMenu g_RootMenu; extern RootConsoleMenu g_RootMenu;

View File

@ -232,7 +232,7 @@ void ShareSystem::DestroyIdentType(IdentityType_t type)
void ShareSystem::RemoveInterfaces(IExtension *pExtension) void ShareSystem::RemoveInterfaces(IExtension *pExtension)
{ {
List<IfaceInfo>::iterator iter = m_Interfaces.begin(); auto iter = m_Interfaces.begin();
while (iter != m_Interfaces.end()) while (iter != m_Interfaces.end())
{ {

View File

@ -37,14 +37,12 @@
#include <am-string.h> #include <am-string.h>
#include <am-utility.h> #include <am-utility.h>
#include <am-refcounting.h> #include <am-refcounting.h>
#include <sh_list.h> #include <list>
#include <sm_hashmap.h> #include <sm_hashmap.h>
#include <sm_namehashset.h> #include <sm_namehashset.h>
#include "common_logic.h" #include "common_logic.h"
#include "Native.h" #include "Native.h"
using namespace SourceHook;
namespace SourceMod namespace SourceMod
{ {
struct IdentityToken_t struct IdentityToken_t
@ -133,7 +131,7 @@ private:
private: private:
typedef NameHashSet<ke::RefPtr<Native>, Native> NativeCache; typedef NameHashSet<ke::RefPtr<Native>, Native> NativeCache;
List<IfaceInfo> m_Interfaces; std::list<IfaceInfo> m_Interfaces;
HandleType_t m_TypeRoot; HandleType_t m_TypeRoot;
IdentityToken_t m_IdentRoot; IdentityToken_t m_IdentRoot;
HandleType_t m_IfaceType; HandleType_t m_IfaceType;

View File

@ -34,17 +34,16 @@
#include "common_logic.h" #include "common_logic.h"
#include <sm_hashmap.h> #include <sm_hashmap.h>
#include <sh_string.h>
#include <sh_vector.h>
#include "sm_memtable.h" #include "sm_memtable.h"
#include "ITextParsers.h" #include "ITextParsers.h"
#include <ITranslator.h> #include <ITranslator.h>
#include "PhraseCollection.h" #include "PhraseCollection.h"
#include <vector>
#include <string>
/* :TODO: write a templatized version of tries? */ /* :TODO: write a templatized version of tries? */
using namespace SourceMod; using namespace SourceMod;
using namespace SourceHook;
class Translator; class Translator;
enum PhraseParseState enum PhraseParseState
@ -83,15 +82,15 @@ private:
void ParseWarning(const char *message, ...); void ParseWarning(const char *message, ...);
private: private:
StringHashMap<int> m_PhraseLookup; StringHashMap<int> m_PhraseLookup;
String m_File; std::string m_File;
Translator *m_pTranslator; Translator *m_pTranslator;
PhraseParseState m_ParseState; PhraseParseState m_ParseState;
int m_CurPhrase; int m_CurPhrase;
BaseMemTable *m_pMemory; BaseMemTable *m_pMemory;
BaseStringTable *m_pStringTab; BaseStringTable *m_pStringTab;
unsigned int m_LangCount; unsigned int m_LangCount;
String m_ParseError; std::string m_ParseError;
String m_LastPhraseString; std::string m_LastPhraseString;
bool m_FileLogged; bool m_FileLogged;
}; };
@ -152,13 +151,13 @@ public: //ITranslator
private: private:
bool AddLanguage(const char *langcode, const char *description); bool AddLanguage(const char *langcode, const char *description);
private: private:
CVector<Language *> m_Languages; std::vector<Language *> m_Languages;
CVector<CPhraseFile *> m_Files; std::vector<CPhraseFile *> m_Files;
BaseStringTable *m_pStringTab; BaseStringTable *m_pStringTab;
StringHashMap<unsigned int> m_LCodeLookup; StringHashMap<unsigned int> m_LCodeLookup;
StringHashMap<unsigned int> m_LAliases; StringHashMap<unsigned int> m_LAliases;
bool m_InLanguageSection; bool m_InLanguageSection;
String m_CustomError; std::string m_CustomError;
unsigned int m_ServerLang; unsigned int m_ServerLang;
char m_InitialLang[4]; char m_InitialLang[4];
}; };

View File

@ -35,6 +35,7 @@
#include <iomanip> #include <iomanip>
#include <sstream> #include <sstream>
#include <list> #include <list>
#include <vector>
#include "common_logic.h" #include "common_logic.h"
#include "Logger.h" #include "Logger.h"
@ -43,9 +44,6 @@
#include <DebugReporter.h> #include <DebugReporter.h>
#include <FrameIterator.h> #include <FrameIterator.h>
#include <sourcehook.h>
#include <sh_memory.h>
#if defined PLATFORM_WINDOWS #if defined PLATFORM_WINDOWS
#include <windows.h> #include <windows.h>
#include "sm_invalidparamhandler.h" #include "sm_invalidparamhandler.h"
@ -54,12 +52,12 @@
#include <unistd.h> #include <unistd.h>
#include <sys/times.h> #include <sys/times.h>
#endif #endif
#include <khook/memory.hpp>
#include <IForwardSys.h> #include <IForwardSys.h>
#include <ILibrarySys.h> #include <ILibrarySys.h>
#include <bridge/include/CoreProvider.h> #include <bridge/include/CoreProvider.h>
#include <bridge/include/IScriptManager.h> #include <bridge/include/IScriptManager.h>
#include <bridge/include/IExtensionBridge.h> #include <bridge/include/IExtensionBridge.h>
#include <sh_vector.h>
using namespace SourceMod; using namespace SourceMod;
using namespace SourcePawn; using namespace SourcePawn;
@ -128,7 +126,7 @@ class CMMPluginIterator
public IPluginsListener public IPluginsListener
{ {
public: public:
CMMPluginIterator(const CVector<SMPlugin *> *list) CMMPluginIterator(const std::vector<SMPlugin *> *list)
: m_hasStarted(false) : m_hasStarted(false)
{ {
for(auto iter = list->begin(); iter != list->end(); ++iter) { for(auto iter = list->begin(); iter != list->end(); ++iter) {
@ -925,21 +923,21 @@ static cell_t StoreToAddress(IPluginContext *pContext, const cell_t *params)
case NumberType_Int8: case NumberType_Int8:
if (updateMemAccess) if (updateMemAccess)
{ {
SourceHook::SetMemAccess(addr, sizeof(uint8_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC); KHook::Memory::SetAccess(addr, sizeof(uint8_t), KHook::Memory::Flags::READ | KHook::Memory::Flags::EXECUTE | KHook::Memory::Flags::WRITE);
} }
*reinterpret_cast<uint8_t*>(addr) = data; *reinterpret_cast<uint8_t*>(addr) = data;
break; break;
case NumberType_Int16: case NumberType_Int16:
if (updateMemAccess) if (updateMemAccess)
{ {
SourceHook::SetMemAccess(addr, sizeof(uint16_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC); KHook::Memory::SetAccess(addr, sizeof(uint16_t), KHook::Memory::Flags::READ | KHook::Memory::Flags::EXECUTE | KHook::Memory::Flags::WRITE);
} }
*reinterpret_cast<uint16_t*>(addr) = data; *reinterpret_cast<uint16_t*>(addr) = data;
break; break;
case NumberType_Int32: case NumberType_Int32:
if (updateMemAccess) if (updateMemAccess)
{ {
SourceHook::SetMemAccess(addr, sizeof(uint32_t), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC); KHook::Memory::SetAccess(addr, sizeof(uint32_t), KHook::Memory::Flags::READ | KHook::Memory::Flags::EXECUTE | KHook::Memory::Flags::WRITE);
} }
*reinterpret_cast<uint32_t*>(addr) = data; *reinterpret_cast<uint32_t*>(addr) = data;
break; break;

View File

@ -290,7 +290,7 @@ public:
private: private:
IDatabase *m_pDatabase; IDatabase *m_pDatabase;
IPluginFunction *m_pFunction; IPluginFunction *m_pFunction;
String m_Query; std::string m_Query;
cell_t m_Data; cell_t m_Data;
IPlugin *me; IPlugin *me;
IQuery *m_pQuery; IQuery *m_pQuery;

View File

@ -29,16 +29,12 @@
* Version: $Id$ * Version: $Id$
*/ */
#include <sh_list.h>
#include <sh_string.h>
#include <ISourceMod.h> #include <ISourceMod.h>
#include "common_logic.h" #include "common_logic.h"
#include "ShareSys.h" #include "ShareSys.h"
#include "PluginSys.h" #include "PluginSys.h"
#include "sprintf.h" #include "sprintf.h"
using namespace SourceHook;
static cell_t s_curparams[SP_MAX_EXEC_PARAMS+1]; static cell_t s_curparams[SP_MAX_EXEC_PARAMS+1];
static FakeNative *s_curnative = NULL; static FakeNative *s_curnative = NULL;
static IPluginContext *s_curcaller = NULL; static IPluginContext *s_curcaller = NULL;

View File

@ -29,7 +29,7 @@
* Version: $Id$ * Version: $Id$
*/ */
#include <sh_list.h> #include <list>
#include <sm_namehashset.h> #include <sm_namehashset.h>
#include "common_logic.h" #include "common_logic.h"
#include "CellArray.h" #include "CellArray.h"
@ -42,8 +42,6 @@
#include <bridge/include/ILogger.h> #include <bridge/include/ILogger.h>
#include <bridge/include/IFileSystemBridge.h> #include <bridge/include/IFileSystemBridge.h>
using namespace SourceHook;
struct maplist_info_t struct maplist_info_t
{ {
bool bIsCompat; bool bIsCompat;
@ -168,7 +166,7 @@ public:
m_pMapCycleFile = bridge->FindConVar("mapcyclefile"); m_pMapCycleFile = bridge->FindConVar("mapcyclefile");
/* Dump everything we know about. */ /* Dump everything we know about. */
List<maplist_info_t *> compat; std::list<maplist_info_t *> compat;
DumpCache(&compat); DumpCache(&compat);
/* All this is to add the default entry back in. */ /* All this is to add the default entry back in. */
@ -206,7 +204,7 @@ public:
} }
/* Now, re-add compat stuff back in if we can. */ /* Now, re-add compat stuff back in if we can. */
List<maplist_info_t *>::iterator iter = compat.begin(); auto iter = compat.begin();
while (iter != compat.end()) while (iter != compat.end())
{ {
if (m_ListLookup.contains((*iter)->name)) if (m_ListLookup.contains((*iter)->name))
@ -666,11 +664,11 @@ private:
return true; return true;
} }
void DumpCache(List<maplist_info_t *> *compat_list) void DumpCache(std::list<maplist_info_t *> *compat_list)
{ {
m_ListLookup.clear(); m_ListLookup.clear();
List<maplist_info_t *>::iterator iter = m_MapLists.begin(); auto iter = m_MapLists.begin();
while (iter != m_MapLists.end()) while (iter != m_MapLists.end())
{ {
if (compat_list != NULL && (*iter)->bIsCompat) if (compat_list != NULL && (*iter)->bIsCompat)
@ -690,7 +688,7 @@ private:
time_t m_ConfigLastChanged; time_t m_ConfigLastChanged;
ConVar *m_pMapCycleFile; ConVar *m_pMapCycleFile;
NameHashSet<maplist_info_t *> m_ListLookup; NameHashSet<maplist_info_t *> m_ListLookup;
List<maplist_info_t *> m_MapLists; std::list<maplist_info_t *> m_MapLists;
MapListState m_CurState; MapListState m_CurState;
unsigned int m_IgnoreLevel; unsigned int m_IgnoreLevel;
maplist_info_t *m_pCurMapList; maplist_info_t *m_pCurMapList;

View File

@ -30,7 +30,6 @@
*/ */
#include "common_logic.h" #include "common_logic.h"
#include <sh_stack.h>
#include <IMenuManager.h> #include <IMenuManager.h>
#include <IPlayerHelpers.h> #include <IPlayerHelpers.h>
#include "DebugReporter.h" #include "DebugReporter.h"
@ -40,6 +39,8 @@
#include <ISourceMod.h> #include <ISourceMod.h>
#include <stdlib.h> #include <stdlib.h>
#include <bridge/include/IScriptManager.h> #include <bridge/include/IScriptManager.h>
#include <stack>
#include <list>
#if defined CreateMenu #if defined CreateMenu
#undef CreateMenu #undef CreateMenu
@ -175,13 +176,13 @@ public:
while (!m_FreePanelHandlers.empty()) while (!m_FreePanelHandlers.empty())
{ {
delete m_FreePanelHandlers.front(); delete m_FreePanelHandlers.top();
m_FreePanelHandlers.pop(); m_FreePanelHandlers.pop();
} }
while (!m_FreeMenuHandlers.empty()) while (!m_FreeMenuHandlers.empty())
{ {
delete m_FreeMenuHandlers.front(); delete m_FreeMenuHandlers.top();
m_FreeMenuHandlers.pop(); m_FreeMenuHandlers.pop();
} }
} }
@ -213,12 +214,12 @@ public:
*/ */
virtual void OnPluginUnloaded(IPlugin *plugin) virtual void OnPluginUnloaded(IPlugin *plugin)
{ {
for (size_t i = 0; i < m_PanelHandlers.size(); i++) for (auto e : m_PanelHandlers)
{ {
if (m_PanelHandlers[i]->m_pPlugin == plugin) if (e->m_pPlugin == plugin)
{ {
m_PanelHandlers[i]->m_pPlugin = NULL; e->m_pPlugin = nullptr;
m_PanelHandlers[i]->m_pFunc = NULL; e->m_pFunc = nullptr;
} }
} }
} }
@ -241,7 +242,7 @@ public:
handler = new CPanelHandler; handler = new CPanelHandler;
m_PanelHandlers.push_back(handler); m_PanelHandlers.push_back(handler);
} else { } else {
handler = m_FreePanelHandlers.front(); handler = m_FreePanelHandlers.top();
m_FreePanelHandlers.pop(); m_FreePanelHandlers.pop();
} }
handler->m_pFunc = pFunction; handler->m_pFunc = pFunction;
@ -263,7 +264,7 @@ public:
{ {
handler = new CMenuHandler(pFunction, flags); handler = new CMenuHandler(pFunction, flags);
} else { } else {
handler = m_FreeMenuHandlers.front(); handler = m_FreeMenuHandlers.top();
m_FreeMenuHandlers.pop(); m_FreeMenuHandlers.pop();
handler->m_pBasic = pFunction; handler->m_pBasic = pFunction;
handler->m_Flags = flags; handler->m_Flags = flags;
@ -280,9 +281,9 @@ public:
private: private:
HandleType_t m_PanelType; HandleType_t m_PanelType;
HandleType_t m_TempPanelType; HandleType_t m_TempPanelType;
CStack<CPanelHandler *> m_FreePanelHandlers; std::stack<CPanelHandler *> m_FreePanelHandlers;
CStack<CMenuHandler *> m_FreeMenuHandlers; std::stack<CMenuHandler *> m_FreeMenuHandlers;
CVector<CPanelHandler *> m_PanelHandlers; std::list<CPanelHandler *> m_PanelHandlers;
} g_MenuHelpers; } g_MenuHelpers;
/** /**

View File

@ -35,8 +35,8 @@
#include <IGameHelpers.h> #include <IGameHelpers.h>
#include <ISourceMod.h> #include <ISourceMod.h>
#include <ITranslator.h> #include <ITranslator.h>
#include <sh_string.h> #include <string>
#include <sh_list.h> #include <list>
#include "GameConfigs.h" #include "GameConfigs.h"
#include "CellArray.h" #include "CellArray.h"
#include "AutoHandleRooter.h" #include "AutoHandleRooter.h"
@ -46,7 +46,6 @@
#include <bridge/include/CoreProvider.h> #include <bridge/include/CoreProvider.h>
#include <bridge/include/IVEngineServerBridge.h> #include <bridge/include/IVEngineServerBridge.h>
using namespace SourceHook;
using namespace SourceMod; using namespace SourceMod;
#ifndef PRIu64 #ifndef PRIu64
@ -75,9 +74,9 @@ class PlayerLogicHelpers :
struct SimpleMultiTargetFilter struct SimpleMultiTargetFilter
{ {
IPlugin *plugin; IPlugin *plugin;
SourceHook::String pattern; std::string pattern;
IPluginFunction *fun; IPluginFunction *fun;
SourceHook::String phrase; std::string phrase;
bool phraseIsML; bool phraseIsML;
SimpleMultiTargetFilter(IPlugin *plugin, const char *pattern, IPluginFunction *fun, SimpleMultiTargetFilter(IPlugin *plugin, const char *pattern, IPluginFunction *fun,
@ -87,7 +86,7 @@ class PlayerLogicHelpers :
} }
}; };
List<SimpleMultiTargetFilter *> simpleMultis; std::list<SimpleMultiTargetFilter *> simpleMultis;
bool filterEnabled; bool filterEnabled;
public: public:
@ -107,7 +106,7 @@ public:
void RemoveMultiTargetFilter(const char *pattern, IPluginFunction *fun) void RemoveMultiTargetFilter(const char *pattern, IPluginFunction *fun)
{ {
List<SimpleMultiTargetFilter *>::iterator iter = simpleMultis.begin(); auto iter = simpleMultis.begin();
while (iter != simpleMultis.end()) { while (iter != simpleMultis.end()) {
if ((*iter)->fun == fun && strcmp((*iter)->pattern.c_str(), pattern) == 0) { if ((*iter)->fun == fun && strcmp((*iter)->pattern.c_str(), pattern) == 0) {
@ -127,9 +126,7 @@ public:
public: //ICommandTargetProcessor public: //ICommandTargetProcessor
bool ProcessCommandTarget(cmd_target_info_t *info) bool ProcessCommandTarget(cmd_target_info_t *info)
{ {
List<SimpleMultiTargetFilter *>::iterator iter; for (auto iter = simpleMultis.begin(); iter != simpleMultis.end(); iter++) {
for (iter = simpleMultis.begin(); iter != simpleMultis.end(); iter++) {
SimpleMultiTargetFilter *smtf = (*iter); SimpleMultiTargetFilter *smtf = (*iter);
if (strcmp(smtf->pattern.c_str(), info->pattern) == 0) { if (strcmp(smtf->pattern.c_str(), info->pattern) == 0) {
CellArray *array = new CellArray(1); CellArray *array = new CellArray(1);
@ -206,7 +203,7 @@ public: //IPluginsListener
void OnPluginDestroyed(IPlugin *plugin) void OnPluginDestroyed(IPlugin *plugin)
{ {
List<SimpleMultiTargetFilter *>::iterator iter = simpleMultis.begin(); auto iter = simpleMultis.begin();
while (iter != simpleMultis.end()) { while (iter != simpleMultis.end()) {
if ((*iter)->plugin != plugin) { if ((*iter)->plugin != plugin) {

View File

@ -34,12 +34,10 @@
#include <IHandleSys.h> #include <IHandleSys.h>
#include <ITimerSystem.h> #include <ITimerSystem.h>
#include <IPluginSys.h> #include <IPluginSys.h>
#include <sh_stack.h> #include <stack>
#include "DebugReporter.h" #include "DebugReporter.h"
#include <bridge/include/CoreProvider.h> #include <bridge/include/CoreProvider.h>
using namespace SourceHook;
#define TIMER_DATA_HNDL_CLOSE (1<<9) #define TIMER_DATA_HNDL_CLOSE (1<<9)
#define TIMER_HNDL_CLOSE (1<<9) #define TIMER_HNDL_CLOSE (1<<9)
@ -74,17 +72,16 @@ public:
TimerInfo *CreateTimerInfo(); TimerInfo *CreateTimerInfo();
void DeleteTimerInfo(TimerInfo *pInfo); void DeleteTimerInfo(TimerInfo *pInfo);
private: private:
CStack<TimerInfo *> m_FreeTimers; std::stack<TimerInfo *> m_FreeTimers;
}; };
TimerNatives::~TimerNatives() TimerNatives::~TimerNatives()
{ {
CStack<TimerInfo *>::iterator iter; while (!m_FreeTimers.empty())
for (iter=m_FreeTimers.begin(); iter!=m_FreeTimers.end(); iter++)
{ {
delete (*iter); delete m_FreeTimers.top();
m_FreeTimers.pop();
} }
m_FreeTimers.popall();
} }
void TimerNatives::OnSourceModAllInitialized() void TimerNatives::OnSourceModAllInitialized()
@ -118,7 +115,7 @@ TimerInfo *TimerNatives::CreateTimerInfo()
{ {
pInfo = new TimerInfo; pInfo = new TimerInfo;
} else { } else {
pInfo = m_FreeTimers.front(); pInfo = m_FreeTimers.top();
m_FreeTimers.pop(); m_FreeTimers.pop();
} }

View File

@ -454,7 +454,7 @@ bool CoreProviderImpl::GetGameName(char *buffer, size_t maxlength)
const char *CoreProviderImpl::GetGameDescription() const char *CoreProviderImpl::GetGameDescription()
{ {
return SERVER_CALL(GetGameDescription)(); return KHook::CallOriginal(&IServerGameDLL::GetGameDescription, gamedll);
} }
const char *CoreProviderImpl::GetSourceEngineName() const char *CoreProviderImpl::GetSourceEngineName()

View File

@ -79,7 +79,7 @@ HandleType_t htConCmdIter = 0;
struct GlobCmdIter struct GlobCmdIter
{ {
bool started; bool started;
List<ConCmdInfo *>::iterator iter; std::list<ConCmdInfo *>::iterator iter;
}; };
class ConsoleHelpers : class ConsoleHelpers :
@ -1056,7 +1056,7 @@ static cell_t ReadCommandIterator(IPluginContext *pContext, const cell_t *params
return pContext->ThrowNativeError("Invalid GlobCmdIter Handle %x", params[1]); return pContext->ThrowNativeError("Invalid GlobCmdIter Handle %x", params[1]);
} }
const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList(); std::list<ConCmdInfo *>& cmds = const_cast<decltype(cmds)>(g_ConCmds.GetCommandList());
if (!iter->started) if (!iter->started)
{ {
@ -1356,7 +1356,7 @@ static cell_t FakeClientCommandKeyValues(IPluginContext *pContext, const cell_t
if (g_Players.InClientCommandKeyValuesHook()) if (g_Players.InClientCommandKeyValuesHook())
{ {
SH_CALL(serverClients, &IServerGameClients::ClientCommandKeyValues)(pPlayer->GetEdict(), pStk->pBase); KHook::CallOriginal(&IServerGameClients::ClientCommandKeyValues, serverClients, pPlayer->GetEdict(), pStk->pBase);
} }
else else
{ {
@ -1395,7 +1395,7 @@ static cell_t sm_CommandIteratorNext(IPluginContext *pContext, const cell_t *par
return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]); return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]);
} }
const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList(); std::list<ConCmdInfo *>& cmds = const_cast<decltype(cmds)>(g_ConCmds.GetCommandList());
if (!iter->started) if (!iter->started)
{ {
@ -1427,7 +1427,7 @@ static cell_t sm_CommandIteratorAdminFlags(IPluginContext *pContext, const cell_
{ {
return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]); return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]);
} }
const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList(); const std::list<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList();
if (!iter->started || iter->iter == cmds.end()) if (!iter->started || iter->iter == cmds.end())
{ {
return pContext->ThrowNativeError("Invalid CommandIterator position"); return pContext->ThrowNativeError("Invalid CommandIterator position");
@ -1448,7 +1448,7 @@ static cell_t sm_CommandIteratorConVarFlags(IPluginContext *pContext, const cell
{ {
return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]); return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]);
} }
const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList(); const std::list<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList();
if (!iter->started || iter->iter == cmds.end()) if (!iter->started || iter->iter == cmds.end())
{ {
return pContext->ThrowNativeError("Invalid CommandIterator position"); return pContext->ThrowNativeError("Invalid CommandIterator position");
@ -1469,7 +1469,7 @@ static cell_t sm_CommandIteratorGetDesc(IPluginContext *pContext, const cell_t *
{ {
return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]); return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]);
} }
const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList(); const std::list<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList();
if (!iter->started || iter->iter == cmds.end()) if (!iter->started || iter->iter == cmds.end())
{ {
return pContext->ThrowNativeError("Invalid CommandIterator position"); return pContext->ThrowNativeError("Invalid CommandIterator position");
@ -1492,7 +1492,7 @@ static cell_t sm_CommandIteratorGetName(IPluginContext *pContext, const cell_t *
{ {
return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]); return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]);
} }
const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList(); const std::list<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList();
if (!iter->started || iter->iter == cmds.end()) if (!iter->started || iter->iter == cmds.end())
{ {
return pContext->ThrowNativeError("Invalid CommandIterator position"); return pContext->ThrowNativeError("Invalid CommandIterator position");
@ -1515,7 +1515,7 @@ static cell_t sm_CommandIteratorPlugin(IPluginContext *pContext, const cell_t *p
{ {
return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]); return pContext->ThrowNativeError("Invalid CommandIterator Handle %x", params[1]);
} }
const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList(); const std::list<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList();
if (!iter->started || iter->iter == cmds.end()) if (!iter->started || iter->iter == cmds.end())
{ {
return pContext->ThrowNativeError("Invalid CommandIterator position"); return pContext->ThrowNativeError("Invalid CommandIterator position");

View File

@ -181,7 +181,7 @@ static cell_t GetGameDescription(IPluginContext *pContext, const cell_t *params)
{ {
description = gamedll->GetGameDescription(); description = gamedll->GetGameDescription();
} else { } else {
description = SERVER_CALL(GetGameDescription)(); description = KHook::CallOriginal(&IServerGameDLL::GetGameDescription, gamedll);
} }
size_t numBytes; size_t numBytes;

View File

@ -499,7 +499,7 @@ static cell_t smn_CreateKeyValues(IPluginContext *pCtx, const cell_t *params)
is_empty = (firstkey[0] == '\0'); is_empty = (firstkey[0] == '\0');
pStk = new KeyValueStack; pStk = new KeyValueStack;
pStk->pBase = new KeyValues(name, is_empty ? NULL : firstkey, (is_empty||(firstvalue[0]=='\0')) ? NULL : firstvalue); pStk->pBase = new KeyValues(name, is_empty ? NULL : firstkey, (is_empty||(firstvalue[0]=='\0')) ? NULL : firstvalue);
pStk->pCurRoot.push(pStk->pBase); pStk->pCurRoot.push_front(pStk->pBase);
return handlesys->CreateHandle(g_KeyValueType, pStk, pCtx->GetIdentity(), g_pCoreIdent, NULL); return handlesys->CreateHandle(g_KeyValueType, pStk, pCtx->GetIdentity(), g_pCoreIdent, NULL);
} }
@ -529,7 +529,7 @@ static cell_t smn_KvJumpToKey(IPluginContext *pCtx, const cell_t *params)
{ {
return 0; return 0;
} }
pStk->pCurRoot.push(pSubKey); pStk->pCurRoot.push_front(pSubKey);
return 1; return 1;
} }
@ -556,7 +556,7 @@ static cell_t smn_KvJumpToKeySymbol(IPluginContext *pCtx, const cell_t *params)
{ {
return 0; return 0;
} }
pStk->pCurRoot.push(pSubKey); pStk->pCurRoot.push_front(pSubKey);
return 1; return 1;
} }
@ -590,7 +590,7 @@ static cell_t smn_KvGotoFirstSubKey(IPluginContext *pCtx, const cell_t *params)
{ {
return 0; return 0;
} }
pStk->pCurRoot.push(pFirstSubKey); pStk->pCurRoot.push_front(pFirstSubKey);
return 1; return 1;
} }
@ -622,8 +622,8 @@ static cell_t smn_KvGotoNextKey(IPluginContext *pCtx, const cell_t *params)
{ {
return 0; return 0;
} }
pStk->pCurRoot.pop(); pStk->pCurRoot.pop_front();
pStk->pCurRoot.push(pSubKey); pStk->pCurRoot.push_front(pSubKey);
return 1; return 1;
} }
@ -648,7 +648,7 @@ static cell_t smn_KvGoBack(IPluginContext *pCtx, const cell_t *params)
{ {
return 0; return 0;
} }
pStk->pCurRoot.pop(); pStk->pCurRoot.pop_front();
return 1; return 1;
} }
@ -674,7 +674,7 @@ static cell_t smn_KvRewind(IPluginContext *pCtx, const cell_t *params)
{ {
while (pStk->pCurRoot.size() > 1) while (pStk->pCurRoot.size() > 1)
{ {
pStk->pCurRoot.pop(); pStk->pCurRoot.pop_front();
} }
} }
else else
@ -682,7 +682,7 @@ static cell_t smn_KvRewind(IPluginContext *pCtx, const cell_t *params)
auto root = pStk->pCurRoot.begin(); auto root = pStk->pCurRoot.begin();
if (root != pStk->pCurRoot.end()) if (root != pStk->pCurRoot.end())
{ {
pStk->pCurRoot.push(*root); pStk->pCurRoot.push_front(*root);
} }
} }
@ -897,7 +897,7 @@ static cell_t smn_KvDeleteThis(IPluginContext *pContext, const cell_t *params)
} }
KeyValues *pValues = pStk->pCurRoot.front(); KeyValues *pValues = pStk->pCurRoot.front();
pStk->pCurRoot.pop(); pStk->pCurRoot.pop_front();
KeyValues *pRoot = pStk->pCurRoot.front(); KeyValues *pRoot = pStk->pCurRoot.front();
/* We have to manually verify this since Valve sucks /* We have to manually verify this since Valve sucks
@ -914,7 +914,7 @@ static cell_t smn_KvDeleteThis(IPluginContext *pContext, const cell_t *params)
pValues->deleteThis(); pValues->deleteThis();
if (pNext) if (pNext)
{ {
pStk->pCurRoot.push(pNext); pStk->pCurRoot.push_front(pNext);
return 1; return 1;
} else { } else {
return -1; return -1;
@ -924,7 +924,7 @@ static cell_t smn_KvDeleteThis(IPluginContext *pContext, const cell_t *params)
} }
/* Push this back on :( */ /* Push this back on :( */
pStk->pCurRoot.push(pValues); pStk->pCurRoot.push_front(pValues);
return 0; return 0;
} }
@ -988,7 +988,7 @@ static cell_t smn_KvSavePosition(IPluginContext *pContext, const cell_t *params)
} }
KeyValues *pValues = pStk->pCurRoot.front(); KeyValues *pValues = pStk->pCurRoot.front();
pStk->pCurRoot.push(pValues); pStk->pCurRoot.push_front(pValues);
return 1; return 1;
} }

View File

@ -33,7 +33,7 @@
#define _INCLUDE_SOURCEMOD_KVWRAPPER_H_ #define _INCLUDE_SOURCEMOD_KVWRAPPER_H_
#include <IHandleSys.h> #include <IHandleSys.h>
#include <sh_stack.h> #include <deque>
using namespace SourceMod; using namespace SourceMod;
@ -42,7 +42,7 @@ class KeyValues;
struct KeyValueStack struct KeyValueStack
{ {
KeyValues *pBase; KeyValues *pBase;
SourceHook::CStack<KeyValues *> pCurRoot; std::deque<KeyValues *> pCurRoot;
bool m_bDeleteOnDestroy = true; bool m_bDeleteOnDestroy = true;
}; };

View File

@ -79,8 +79,7 @@ static cell_t sm_GetMapHistory(IPluginContext *pCtx, const cell_t *params)
return pCtx->ThrowNativeError("Invalid Map History Index"); return pCtx->ThrowNativeError("Invalid Map History Index");
} }
SourceHook::List<MapChangeData *>::iterator iter; auto iter = g_NextMap.m_mapHistory.end();
iter = g_NextMap.m_mapHistory.end();
iter--; iter--;
for (int i=0; i<params[1]; i++) for (int i=0; i<params[1]; i++)

View File

@ -51,8 +51,8 @@ bf_read g_ReadBitBuf;
int g_MsgPlayers[SM_MAXPLAYERS+1]; int g_MsgPlayers[SM_MAXPLAYERS+1];
bool g_IsMsgInExec = false; bool g_IsMsgInExec = false;
typedef List<MsgListenerWrapper *> MsgWrapperList; typedef std::list<MsgListenerWrapper *> MsgWrapperList;
typedef List<MsgListenerWrapper *>::iterator MsgWrapperIter; typedef MsgWrapperList::iterator MsgWrapperIter;
class UsrMessageNatives : class UsrMessageNatives :
public SMGlobalClass, public SMGlobalClass,
@ -72,17 +72,15 @@ public:
bool FindListener(int msgid, IPluginContext *pCtx, IPluginFunction *pHook, bool intercept, MsgWrapperIter *iter); bool FindListener(int msgid, IPluginContext *pCtx, IPluginFunction *pHook, bool intercept, MsgWrapperIter *iter);
bool DeleteListener(IPluginContext *pCtx, MsgWrapperIter iter); bool DeleteListener(IPluginContext *pCtx, MsgWrapperIter iter);
private: private:
CStack<MsgListenerWrapper *> m_FreeListeners; std::stack<MsgListenerWrapper *> m_FreeListeners;
}; };
UsrMessageNatives::~UsrMessageNatives() UsrMessageNatives::~UsrMessageNatives()
{ {
CStack<MsgListenerWrapper *>::iterator iter; while (!m_FreeListeners.empty()) {
for (iter=m_FreeListeners.begin(); iter!=m_FreeListeners.end(); iter++) delete m_FreeListeners.top();
{ m_FreeListeners.pop();
delete (*iter);
} }
m_FreeListeners.popall();
} }
void UsrMessageNatives::OnSourceModAllInitialized() void UsrMessageNatives::OnSourceModAllInitialized()
@ -175,13 +173,13 @@ MsgListenerWrapper *UsrMessageNatives::CreateListener(IPluginContext *pCtx)
{ {
pListener = new MsgListenerWrapper; pListener = new MsgListenerWrapper;
} else { } else {
pListener = m_FreeListeners.front(); pListener = m_FreeListeners.top();
m_FreeListeners.pop(); m_FreeListeners.pop();
} }
if (!pl->GetProperty("MsgListeners", reinterpret_cast<void **>(&pList))) if (!pl->GetProperty("MsgListeners", reinterpret_cast<void **>(&pList)))
{ {
pList = new List<MsgListenerWrapper *>; pList = new std::list<MsgListenerWrapper *>;
pl->SetProperty("MsgListeners", pList); pl->SetProperty("MsgListeners", pList);
} }

View File

@ -48,8 +48,6 @@ ISmmPluginManager *g_pMMPlugins = NULL;
CGlobalVars *gpGlobals = NULL; CGlobalVars *gpGlobals = NULL;
ICvar *icvar = NULL; ICvar *icvar = NULL;
IGameEventManager2 *gameevents = NULL; IGameEventManager2 *gameevents = NULL;
CallClass<IVEngineServer> *enginePatch = NULL;
CallClass<IServerGameDLL> *gamedllPatch = NULL;
IPlayerInfoManager *playerinfo = NULL; IPlayerInfoManager *playerinfo = NULL;
IBaseFileSystem *basefilesystem = NULL; IBaseFileSystem *basefilesystem = NULL;
IFileSystem *filesystem = NULL; IFileSystem *filesystem = NULL;

View File

@ -40,6 +40,7 @@
#include <filesystem.h> #include <filesystem.h>
#include <IEngineSound.h> #include <IEngineSound.h>
#include <toolframework/itoolentity.h> #include <toolframework/itoolentity.h>
#include <khook.hpp>
/** /**
* @file Contains wrappers around required Metamod:Source API exports * @file Contains wrappers around required Metamod:Source API exports
@ -78,8 +79,6 @@ extern ICvar *icvar;
extern ISmmPluginManager *g_pMMPlugins; extern ISmmPluginManager *g_pMMPlugins;
extern CGlobalVars *gpGlobals; extern CGlobalVars *gpGlobals;
extern IGameEventManager2 *gameevents; extern IGameEventManager2 *gameevents;
extern SourceHook::CallClass<IVEngineServer> *enginePatch;
extern SourceHook::CallClass<IServerGameDLL> *gamedllPatch;
extern IPlayerInfoManager *playerinfo; extern IPlayerInfoManager *playerinfo;
extern IBaseFileSystem *basefilesystem; extern IBaseFileSystem *basefilesystem;
extern IFileSystem *filesystem; extern IFileSystem *filesystem;
@ -91,9 +90,6 @@ extern IServerPluginHelpers *serverpluginhelpers;
extern IServerPluginCallbacks *vsp_interface; extern IServerPluginCallbacks *vsp_interface;
extern int vsp_version; extern int vsp_version;
#define ENGINE_CALL(func) SH_CALL(enginePatch, &IVEngineServer::func)
#define SERVER_CALL(func) SH_CALL(gamedllPatch, &IServerGameDLL::func)
PLUGIN_GLOBALVARS(); PLUGIN_GLOBALVARS();
#endif //_INCLUDE_SOURCEMOD_MM_API_H_ #endif //_INCLUDE_SOURCEMOD_MM_API_H_

View File

@ -32,7 +32,7 @@
#include <stdio.h> #include <stdio.h>
#include "sourcemod.h" #include "sourcemod.h"
#include "sourcemm_api.h" #include "sourcemm_api.h"
#include <sh_string.h> #include <string>
#include "CoreConfig.h" #include "CoreConfig.h"
#include "Logger.h" #include "Logger.h"
#include "sm_stringutil.h" #include "sm_stringutil.h"
@ -49,17 +49,12 @@
#include <bridge/include/IProviderCallbacks.h> #include <bridge/include/IProviderCallbacks.h>
#include <bridge/include/ILogger.h> #include <bridge/include/ILogger.h>
SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool); /**/
SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
SH_DECL_HOOK1_void(IServerGameDLL, Think, SH_NOATTRIB, false, bool);
SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
SH_DECL_HOOK0(IVEngineServer, GetMapEntitiesString, SH_NOATTRIB, 0, const char *);
SourceModBase g_SourceMod; SourceModBase g_SourceMod;
ke::RefPtr<ke::SharedLib> g_JIT; ke::RefPtr<ke::SharedLib> g_JIT;
SourceHook::String g_BaseDir; std::string g_BaseDir;
ISourcePawnEngine *g_pSourcePawn = NULL; ISourcePawnEngine *g_pSourcePawn = NULL;
ISourcePawnEngine2 *g_pSourcePawn2 = NULL; ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
ISourcePawnEnvironment *g_pPawnEnv = NULL; ISourcePawnEnvironment *g_pPawnEnv = NULL;
@ -93,13 +88,32 @@ void ShutdownJIT()
g_JIT = nullptr; g_JIT = nullptr;
} }
SourceModBase::SourceModBase() SourceModBase::SourceModBase() :
m_HookLevelInit(&IServerGameDLL::LevelInit, this, &SourceModBase::Hook_LevelInit, nullptr),
m_HookLevelShutdown(&IServerGameDLL::LevelShutdown, this, &SourceModBase::Hook_LevelShutdown, nullptr),
m_HookGameFrame(&IServerGameDLL::GameFrame, this, &SourceModBase::Hook_GameFrame, nullptr),
m_HookThink(&IServerGameDLL::Think, this, &SourceModBase::Hook_Think, nullptr),
m_HookGetMapEntitiesString(&IVEngineServer::GetMapEntitiesString, this, &SourceModBase::Hook_GetMapEntitiesString, nullptr)
{ {
m_IsMapLoading = false; m_IsMapLoading = false;
m_ExecPluginReload = false; m_ExecPluginReload = false;
m_GotBasePath = false; m_GotBasePath = false;
} }
KHook::Return<void> SourceModBase::Hook_GameFrame(IServerGameDLL*, bool simulating)
{
g_Timers.GameFrame(simulating);
return { KHook::Action::Ignore };
}
KHook::Return<void> SourceModBase::Hook_Think(IServerGameDLL*, bool simulating)
{
logicore.callbacks->OnThink(simulating);
return { KHook::Action::Ignore };
}
ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key, ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
const char *value, const char *value,
ConfigSource source, ConfigSource source,
@ -278,8 +292,8 @@ bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late
sSourceModInitialized = true; sSourceModInitialized = true;
/* Hook this now so we can detect startup without calling StartSourceMod() */ /* Hook this now so we can detect startup without calling StartSourceMod() */
SH_ADD_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(this, &SourceModBase::LevelInit), false); m_HookLevelInit.Add(gamedll);
SH_ADD_HOOK(IVEngineServer, GetMapEntitiesString, engine, SH_MEMBER(this, &SourceModBase::GetMapEntitiesString), false); m_HookGetMapEntitiesString.Add(engine);
/* Only load if we're not late */ /* Only load if we're not late */
if (!late) if (!late)
@ -292,11 +306,8 @@ bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late
void SourceModBase::StartSourceMod(bool late) void SourceModBase::StartSourceMod(bool late)
{ {
SH_ADD_HOOK(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false); m_HookLevelShutdown.Add(gamedll);
SH_ADD_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false); m_HookGameFrame.Add(gamedll);
enginePatch = SH_GET_CALLCLASS(engine);
gamedllPatch = SH_GET_CALLCLASS(gamedll);
sCoreProviderImpl.InitializeBridge(); sCoreProviderImpl.InitializeBridge();
@ -370,12 +381,11 @@ void SourceModBase::StartSourceMod(bool late)
{ {
g_pPawnEnv->EnableDebugBreak(); g_pPawnEnv->EnableDebugBreak();
} }
m_HookThink.Add(gamedll);
SH_ADD_HOOK(IServerGameDLL, Think, gamedll, SH_MEMBER(logicore.callbacks, &IProviderCallbacks::OnThink), false);
} }
static bool g_LevelEndBarrier = false; static bool g_LevelEndBarrier = false;
bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) KHook::Return<bool> SourceModBase::Hook_LevelInit(IServerGameDLL*, char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
{ {
/* Seed rand() globally per map */ /* Seed rand() globally per map */
srand(time(NULL)); srand(time(NULL));
@ -436,23 +446,23 @@ bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, ch
if (!success) if (!success)
{ {
logger->LogError("Map entity lump parsing for %s failed with error code %d on position %d", pMapName, parseError, position); logger->LogError("Map entity lump parsing for %s failed with error code %d on position %d", pMapName, parseError, position);
RETURN_META_VALUE(MRES_IGNORED, true); return { KHook::Action::Ignore };
} }
RETURN_META_VALUE_NEWPARAMS(MRES_HANDLED, true, &IServerGameDLL::LevelInit, (pMapName, logicore.GetEntityLumpString(), pOldLevel, pLandmarkName, loadGame, background)); return KHook::Recall(KHook::Return<bool>{KHook::Action::Override, true}, (pMapName, logicore.GetEntityLumpString(), pOldLevel, pLandmarkName, loadGame, background));
} }
const char *SourceModBase::GetMapEntitiesString() KHook::Return<const char*> SourceModBase::Hook_GetMapEntitiesString(IVEngineServer*)
{ {
const char *pNewMapEntities = logicore.GetEntityLumpString(); const char *pNewMapEntities = logicore.GetEntityLumpString();
if (pNewMapEntities != nullptr) if (pNewMapEntities != nullptr)
{ {
RETURN_META_VALUE(MRES_SUPERCEDE, pNewMapEntities); return { KHook::Action::Supersede, pNewMapEntities };
} }
RETURN_META_VALUE(MRES_IGNORED, NULL); return { KHook::Action::Ignore };
} }
void SourceModBase::LevelShutdown() KHook::Return<void> SourceModBase::Hook_LevelShutdown(IServerGameDLL*)
{ {
if (g_LevelEndBarrier) if (g_LevelEndBarrier)
{ {
@ -479,6 +489,8 @@ void SourceModBase::LevelShutdown()
scripts->RefreshAll(); scripts->RefreshAll();
m_ExecPluginReload = false; m_ExecPluginReload = false;
} }
return { KHook::Action::Ignore };
} }
bool SourceModBase::IsMapLoading() const bool SourceModBase::IsMapLoading() const
@ -563,13 +575,13 @@ void SourceModBase::CloseSourceMod()
if (!sSourceModInitialized) if (!sSourceModInitialized)
return; return;
SH_REMOVE_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(this, &SourceModBase::LevelInit), false); m_HookLevelInit.Remove(gamedll);
SH_REMOVE_HOOK(IVEngineServer, GetMapEntitiesString, engine, SH_MEMBER(this, &SourceModBase::GetMapEntitiesString), false); m_HookGetMapEntitiesString.Remove(engine);
if (g_Loaded) if (g_Loaded)
{ {
/* Force a level end */ /* Force a level end */
LevelShutdown(); Hook_LevelShutdown(gamedll);
ShutdownServices(); ShutdownServices();
} }
@ -616,21 +628,9 @@ void SourceModBase::ShutdownServices()
pBase = pBase->m_pGlobalClassNext; pBase = pBase->m_pGlobalClassNext;
} }
if (enginePatch) m_HookLevelShutdown.Remove(gamedll);
{ m_HookGameFrame.Remove(gamedll);
SH_RELEASE_CALLCLASS(enginePatch); m_HookThink.Remove(gamedll);
enginePatch = NULL;
}
if (gamedllPatch)
{
SH_RELEASE_CALLCLASS(gamedllPatch);
gamedllPatch = NULL;
}
SH_REMOVE_HOOK(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false);
SH_REMOVE_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false);
SH_REMOVE_HOOK(IServerGameDLL, Think, gamedll, SH_MEMBER(logicore.callbacks, &IProviderCallbacks::OnThink), false);
} }
void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...) void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
@ -765,7 +765,7 @@ void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
{ {
if (m_frame_hooks[i] == hook) if (m_frame_hooks[i] == hook)
{ {
m_frame_hooks.erase(m_frame_hooks.iterAt(i)); m_frame_hooks.erase(m_frame_hooks.begin() + i);
return; return;
} }
} }
@ -821,9 +821,7 @@ int SourceModBase::GetPluginId()
int SourceModBase::GetShApiVersion() int SourceModBase::GetShApiVersion()
{ {
int api, impl; int api = 999, impl = 999;
g_SMAPI->GetShVersions(api, impl);
return api; return api;
} }

View File

@ -34,10 +34,9 @@
#include "sm_globals.h" #include "sm_globals.h"
#include <ISourceMod.h> #include <ISourceMod.h>
#include <sh_stack.h> #include <stack>
#include <sh_vector.h> #include <vector>
#include <khook.hpp>
using namespace SourceHook;
#if defined _DEBUG #if defined _DEBUG
# define IF_DEBUG_SPEW # define IF_DEBUG_SPEW
@ -76,16 +75,6 @@ public:
*/ */
void CloseSourceMod(); void CloseSourceMod();
/**
* @brief Map change hook
*/
bool LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
/**
* @brief Level shutdown hook
*/
void LevelShutdown();
/** /**
* @brief Returns whether or not a map load is in progress * @brief Returns whether or not a map load is in progress
*/ */
@ -140,7 +129,6 @@ public: // ISourceMod
private: private:
void ShutdownServices(); void ShutdownServices();
private: private:
const char* GetMapEntitiesString();
char m_SMBaseDir[PLATFORM_MAX_PATH]; char m_SMBaseDir[PLATFORM_MAX_PATH];
char m_SMRelDir[PLATFORM_MAX_PATH]; char m_SMRelDir[PLATFORM_MAX_PATH];
char m_ModDir[32]; char m_ModDir[32];
@ -149,7 +137,18 @@ private:
bool m_ExecOnMapEnd; bool m_ExecOnMapEnd;
unsigned int m_target; unsigned int m_target;
bool m_GotBasePath; bool m_GotBasePath;
CVector<GAME_FRAME_HOOK> m_frame_hooks; std::vector<GAME_FRAME_HOOK> m_frame_hooks;
protected:
KHook::Virtual<class IServerGameDLL, bool, const char *, const char *, const char *, const char *, bool, bool> m_HookLevelInit;
KHook::Return<bool> Hook_LevelInit(class IServerGameDLL*, char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
KHook::Virtual<class IServerGameDLL, void> m_HookLevelShutdown;
KHook::Return<void> Hook_LevelShutdown(class IServerGameDLL*);
KHook::Virtual<class IServerGameDLL, void, bool> m_HookGameFrame;
KHook::Return<void> Hook_GameFrame(class IServerGameDLL*, bool);
KHook::Virtual<class IServerGameDLL, void, bool> m_HookThink;
KHook::Return<void> Hook_Think(class IServerGameDLL*, bool);
KHook::Virtual<class IVEngineServer, const char*> m_HookGetMapEntitiesString;
KHook::Return<const char*> Hook_GetMapEntitiesString(class IVEngineServer*);
}; };
void UTIL_ConsolePrintVa(const char *fmt, va_list ap); void UTIL_ConsolePrintVa(const char *fmt, va_list ap);

View File

@ -34,9 +34,7 @@
#include <new> #include <new>
#include <stdlib.h> #include <stdlib.h>
#include <sh_stack.h> #include <stack>
using namespace SourceHook;
/* /*
A circular, doubly-linked List with one sentinel node A circular, doubly-linked List with one sentinel node
@ -109,7 +107,7 @@ public:
while (!m_FreeNodes.empty()) while (!m_FreeNodes.empty())
{ {
free(m_FreeNodes.front()); free(m_FreeNodes.top());
m_FreeNodes.pop(); m_FreeNodes.pop();
} }
} }
@ -122,7 +120,7 @@ public:
{ {
node = (QueueNode *)malloc(sizeof(QueueNode)); node = (QueueNode *)malloc(sizeof(QueueNode));
} else { } else {
node = m_FreeNodes.front(); node = m_FreeNodes.top();
m_FreeNodes.pop(); m_FreeNodes.pop();
} }
@ -169,7 +167,7 @@ public:
private: private:
QueueNode *m_Head; QueueNode *m_Head;
size_t m_Size; size_t m_Size;
CStack<QueueNode *> m_FreeNodes; std::stack<QueueNode *> m_FreeNodes;
public: public:
class iterator class iterator
{ {