mmsplugin.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**
  2. * vim: set ts=4 sw=4 tw=99 noet :
  3. * ======================================================
  4. * TF2 Dynamic Schema Injector
  5. * Written by nosoop
  6. * ======================================================
  7. */
  8. #include <stdio.h>
  9. #include "mmsplugin.h"
  10. #include <utlmap.h>
  11. #include <utlstring.h>
  12. #include <KeyValues.h>
  13. #include <filesystem.h>
  14. #include "memscan.h"
  15. SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
  16. SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, 0, bool, char const *, char const *, char const *, char const *, bool, bool);
  17. DynSchema g_Plugin;
  18. IServerGameDLL *server = nullptr;
  19. IVEngineServer *engine = NULL;
  20. IFileSystem *filesystem = nullptr;
  21. PLUGIN_EXPOSE(DynSchema, g_Plugin);
  22. class ISchemaAttributeType;
  23. // this may need to be updated in the future
  24. class CEconItemAttributeDefinition
  25. {
  26. public:
  27. // TODO implementing ~CEconItemAttributeDefinition segfaults. not sure what's up.
  28. // ideally we implement it to match the game so InsertOrReplace is sure to work correctly
  29. /* 0x00 */ KeyValues *m_KeyValues;
  30. /* 0x04 */ unsigned short m_iIndex;
  31. /* 0x08 */ ISchemaAttributeType *m_AttributeType;
  32. /* 0x0c */ bool m_bHidden;
  33. /* 0x0d */ bool m_bForceOutputDescription;
  34. /* 0x0e */ bool m_bStoreAsInteger;
  35. /* 0x0f */ bool m_bInstanceData;
  36. /* 0x10 */ int m_iAssetClassExportType;
  37. /* 0x14 */ int m_iAssetClassBucket;
  38. /* 0x18 */ bool m_bIsSetBonus;
  39. /* 0x1c */ int m_iIsUserGenerated;
  40. /* 0x20 */ int m_iEffectType;
  41. /* 0x24 */ int m_iDescriptionFormat;
  42. /* 0x28 */ char *m_pszDescriptionString;
  43. /* 0x2c */ char *m_pszArmoryDesc;
  44. /* 0x30 */ char *m_pszName;
  45. /* 0x34 */ char *m_pszAttributeClass;
  46. /* 0x38 */ bool m_bCanAffectMarketName;
  47. /* 0x39 */ bool m_bCanAffectRecipeCompName;
  48. /* 0x3c */ int m_nTagHandle;
  49. /* 0x40 */ string_t m_iszAttributeClass;
  50. };
  51. // binary refers to 0x58 when iterating over the attribute map, so we'll refer to that value
  52. // we could also do a runtime assertion
  53. static_assert(sizeof(CEconItemAttributeDefinition) + 0x14 == 0x58, "CEconItemAttributeDefinition size mismatch");
  54. // pointer to item schema attribute map singleton
  55. using AttributeMap = CUtlMap<int, CEconItemAttributeDefinition, int>;
  56. AttributeMap *g_SchemaAttributes;
  57. typedef uintptr_t (*GetEconItemSchema_fn)(void);
  58. GetEconItemSchema_fn fnGetEconItemSchema = nullptr;
  59. // https://www.unknowncheats.me/wiki/Calling_Functions_From_Injected_Library_Using_Function_Pointers_in_C%2B%2B
  60. #ifdef WIN32
  61. typedef bool (__thiscall *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  62. #elif defined(_LINUX)
  63. typedef bool (__cdecl *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  64. #endif
  65. CEconItemAttributeInitFromKV_fn fnItemAttributeInitFromKV = nullptr;
  66. const char* NATIVE_ATTRIB_DIR = "addons/sourcemod/configs/tf2nativeattribs";
  67. bool DynSchema::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
  68. {
  69. PLUGIN_SAVEVARS();
  70. GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
  71. GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
  72. GET_V_IFACE_CURRENT(GetFileSystemFactory, filesystem, IFileSystem, FILESYSTEM_INTERFACE_VERSION);
  73. SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  74. // get the base address of the server
  75. #if _WINDOWS
  76. CWinLibInfo lib(server);
  77. lib.LocatePattern("\xE8\x2A\x2A\x2A\x2A\x83\xC0\x04\xC3", 9, (void**) &fnGetEconItemSchema);
  78. lib.LocatePattern("\x55\x8B\xEC\x53\x8B\x5D\x08\x56\x8B\xF1\x8B\xCB\x57\xE8\x2A\x2A\x2A\x2A", 18, (void**) &fnItemAttributeInitFromKV);
  79. #elif _LINUX
  80. CLinuxLibInfo lib(server);
  81. lib.LocateSymbol("_ZN28CEconItemAttributeDefinition11BInitFromKVEP9KeyValuesP10CUtlVectorI10CUtlString10CUtlMemoryIS3_iEE",
  82. (void**) &fnItemAttributeInitFromKV);
  83. lib.LocateSymbol("_Z15GEconItemSchemav", (void**) &fnGetEconItemSchema);
  84. #endif
  85. if (!fnItemAttributeInitFromKV || !fnGetEconItemSchema) {
  86. META_CONPRINTF("Failed to get GEIS or BIFKV\n");
  87. return false;
  88. }
  89. // is this late enough in the MM:S load stage? we might just have to hold the function
  90. g_SchemaAttributes = reinterpret_cast<AttributeMap*>(fnGetEconItemSchema() + 0x1BC);
  91. return true;
  92. }
  93. bool DynSchema::Unload(char *error, size_t maxlen) {
  94. SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  95. return true;
  96. }
  97. /**
  98. * Initializes a CEconItemAttributeDefinition from a KeyValues definition, then inserts or
  99. * replaces the appropriate entry in the schema.
  100. */
  101. bool InsertOrReplaceAttribute(KeyValues *pAttribKV) {
  102. /**
  103. * TODO implement special handling when "auto" is provided; use an autoincrementing value
  104. * that checks for a free slot in the attribute mapping, then internally map the attribute
  105. * name to that value for persistence and so we don't add that attribute multiple times
  106. */
  107. int attrdef = atoi(pAttribKV->GetName());
  108. if (attrdef <= 0) {
  109. return false;
  110. }
  111. // only replace existing injected attributes; fail on schema attributes
  112. auto existingIndex = g_SchemaAttributes->Find(attrdef);
  113. if (existingIndex != g_SchemaAttributes->InvalidIndex()) {
  114. auto &existingAttr = g_SchemaAttributes->Element(existingIndex);
  115. if (!existingAttr.m_KeyValues->GetBool("injected")) {
  116. META_CONPRINTF("WARN: Not overriding native attribute '%s'\n",
  117. existingAttr.m_pszName);
  118. return false;
  119. }
  120. }
  121. // embed additional custom data into attribute KV; econdata and the like can deal with this
  122. // one could also add this data into the file itself, but this leaves less room for error
  123. pAttribKV->SetBool("injected", true);
  124. CEconItemAttributeDefinition def;
  125. fnItemAttributeInitFromKV(&def, pAttribKV, nullptr);
  126. // TODO verify that this doesn't leak, or just shrug it off
  127. g_SchemaAttributes->InsertOrReplace(attrdef, def);
  128. return true;
  129. }
  130. bool DynSchema::Hook_LevelInitPost(const char *pMapName, char const *pMapEntities,
  131. char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) {
  132. // this hook should fire shortly after the schema is (re)initialized
  133. char game_path[256];
  134. engine->GetGameDir(game_path, sizeof(game_path));
  135. char buffer[1024];
  136. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s",
  137. game_path, "addons/dynattrs/items_dynamic.txt");
  138. // always initialize attributes -- it's better than losing attributes on schema reinit
  139. // coughhiddendevattributescough
  140. // collect raw attribute keyvalue entries scattered across files
  141. KeyValues::AutoDelete rawAttributes("attributes");
  142. // read our own dynamic schema file -- this one supports other sections
  143. KeyValues::AutoDelete pKVMainConfig("DynamicSchema");
  144. if (pKVMainConfig->LoadFromFile(filesystem, buffer)) {
  145. KeyValues *pKVAttributes = pKVMainConfig->FindKey( "attributes" );
  146. if (pKVAttributes) {
  147. rawAttributes->RecursiveMergeKeyValues(pKVAttributes);
  148. META_CONPRINTF("Successfully injected custom schema %s\n", buffer);
  149. } else {
  150. META_CONPRINTF("Failed to inject custom schema %s\n", buffer);
  151. }
  152. }
  153. // iterate over TF2 Hidden Dev Attributes KV format
  154. // https://forums.alliedmods.net/showthread.php?t=326853
  155. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s/*", game_path, NATIVE_ATTRIB_DIR);
  156. FileFindHandle_t findHandle;
  157. const char *filename = filesystem->FindFirst(buffer, &findHandle);
  158. while (filename) {
  159. char pathbuf[1024];
  160. g_SMAPI->PathFormat(pathbuf, sizeof(pathbuf), "%s/%s/%s", game_path,
  161. NATIVE_ATTRIB_DIR, filename);
  162. if (!filesystem->FindIsDirectory(findHandle)) {
  163. KeyValues::AutoDelete nativeAttribConfig("attributes");
  164. nativeAttribConfig->LoadFromFile(filesystem, pathbuf);
  165. rawAttributes->RecursiveMergeKeyValues(nativeAttribConfig);
  166. META_CONPRINTF("Discovered custom schema %s\n", pathbuf);
  167. }
  168. filename = filesystem->FindNext(findHandle);
  169. }
  170. filesystem->FindClose(findHandle);
  171. // perhaps add some other validations before we actually process our attributes?
  172. // TODO ensure the name doesn't clash with existing / newly injected attributes
  173. // finally process our attributes
  174. FOR_EACH_TRUE_SUBKEY(rawAttributes, kv) {
  175. InsertOrReplaceAttribute(kv);
  176. }
  177. return true;
  178. }
  179. void DynSchema::AllPluginsLoaded() {
  180. /* This is where we'd do stuff that relies on the mod or other plugins
  181. * being initialized (for example, cvars added and events registered).
  182. */
  183. }
  184. bool DynSchema::Pause(char *error, size_t maxlen) {
  185. return true;
  186. }
  187. bool DynSchema::Unpause(char *error, size_t maxlen) {
  188. return true;
  189. }
  190. const char *DynSchema::GetLicense() {
  191. return "Proprietary";
  192. }
  193. const char *DynSchema::GetVersion() {
  194. return "1.2.1";
  195. }
  196. const char *DynSchema::GetDate() {
  197. return __DATE__;
  198. }
  199. const char *DynSchema::GetLogTag() {
  200. return "dynschema";
  201. }
  202. const char *DynSchema::GetAuthor() {
  203. return "nosoop";
  204. }
  205. const char *DynSchema::GetDescription() {
  206. return "Injects user-defined content into the game schema";
  207. }
  208. const char *DynSchema::GetName() {
  209. return "TF2 Dynamic Schema";
  210. }
  211. const char *DynSchema::GetURL() {
  212. return "https://git.csrd.science/";
  213. }