mmsplugin.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. #if WINDOWS
  15. #include <windows.h>
  16. #elif _LINUX
  17. #include <fcntl.h>
  18. #include <gelf.h>
  19. #endif
  20. SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
  21. SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, 0, bool, char const *, char const *, char const *, char const *, bool, bool);
  22. DynSchema g_Plugin;
  23. IServerGameDLL *server = nullptr;
  24. IVEngineServer *engine = NULL;
  25. IBaseFileSystem *basefilesystem = nullptr;
  26. PLUGIN_EXPOSE(DynSchema, g_Plugin);
  27. class ISchemaAttributeType;
  28. // this may need to be updated in the future
  29. class CEconItemAttributeDefinition
  30. {
  31. public:
  32. /* 0x00 */ KeyValues *m_KeyValues;
  33. /* 0x04 */ unsigned short m_iIndex;
  34. /* 0x08 */ ISchemaAttributeType *m_AttributeType;
  35. /* 0x0c */ bool m_bHidden;
  36. /* 0x0d */ bool m_bForceOutputDescription;
  37. /* 0x0e */ bool m_bStoreAsInteger;
  38. /* 0x0f */ bool m_bInstanceData;
  39. /* 0x10 */ int m_iAssetClassExportType;
  40. /* 0x14 */ int m_iAssetClassBucket;
  41. /* 0x18 */ bool m_bIsSetBonus;
  42. /* 0x1c */ int m_iIsUserGenerated;
  43. /* 0x20 */ int m_iEffectType;
  44. /* 0x24 */ int m_iDescriptionFormat;
  45. /* 0x28 */ char *m_pszDescriptionString;
  46. /* 0x2c */ char *m_pszArmoryDesc;
  47. /* 0x30 */ char *m_pszName;
  48. /* 0x34 */ char *m_pszAttributeClass;
  49. /* 0x38 */ bool m_bCanAffectMarketName;
  50. /* 0x39 */ bool m_bCanAffectRecipeCompName;
  51. /* 0x3c */ int m_nTagHandle;
  52. /* 0x40 */ string_t m_iszAttributeClass;
  53. };
  54. // binary refers to 0x58 when iterating over the attribute map, so we'll refer to that value
  55. // we could also do a runtime assertion
  56. static_assert(sizeof(CEconItemAttributeDefinition) + 0x14 == 0x58, "CEconItemAttributeDefinition size mismatch");
  57. // pointer to item schema attribute map singleton
  58. using AttributeMap = CUtlMap<int, CEconItemAttributeDefinition, int>;
  59. AttributeMap *g_SchemaAttributes;
  60. using GetEconItemSchemaFn_t = uintptr_t();
  61. GetEconItemSchemaFn_t *fnGetEconItemSchema = nullptr;
  62. // https://www.unknowncheats.me/wiki/Calling_Functions_From_Injected_Library_Using_Function_Pointers_in_C%2B%2B
  63. #ifdef WIN32
  64. typedef bool (__thiscall *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  65. #elif defined(_LINUX)
  66. typedef bool (__cdecl *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  67. #endif
  68. CEconItemAttributeInitFromKV_fn fnItemAttributeInitFromKV = nullptr;
  69. uintptr_t FindPattern(uintptr_t start, uintptr_t end, const char* pattern, size_t length) {
  70. uintptr_t ptr = start;
  71. bool f;
  72. while (ptr < end - length) {
  73. f = true;
  74. const char* cur = reinterpret_cast<char*>(ptr);
  75. for (register size_t i = 0; i < length; i++) {
  76. if (pattern[i] != '\x2A' && pattern[i] != cur[i]) {
  77. f = false;
  78. break;
  79. }
  80. }
  81. if (f) {
  82. return ptr;
  83. }
  84. ptr++;
  85. }
  86. return 0;
  87. }
  88. bool DynSchema::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
  89. {
  90. PLUGIN_SAVEVARS();
  91. GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
  92. GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
  93. GET_V_IFACE_CURRENT(GetFileSystemFactory, basefilesystem, IBaseFileSystem, BASEFILESYSTEM_INTERFACE_VERSION);
  94. SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  95. // get the base address of the server
  96. // TODO windows support
  97. #if WINDOWS
  98. MEMORY_BASIC_INFORMATION info;
  99. if (!VirtualQuery(server, &info, sizeof(MEMORY_BASIC_INFORMATION))) {
  100. return false;
  101. }
  102. uintptr_t base = reinterpret_cast<uintptr_t>(info.AllocationBase);
  103. IMAGE_DOS_HEADER *dos = reinterpret_cast<IMAGE_DOS_HEADER *>(base);
  104. IMAGE_NT_HEADERS *pe = reinterpret_cast<IMAGE_NT_HEADERS *>(base + dos->e_lfanew);
  105. IMAGE_OPTIONAL_HEADER *opt = &pe->OptionalHeader;
  106. size_t size = opt->SizeOfImage;
  107. fnGetEconItemSchema = (GetEconItemSchemaFn_t*) (FindPattern(base, base + size, "\xE8\x2A\x2A\x2A\x2A\x83\xC0\x04\xC3", 9));
  108. fnItemAttributeInitFromKV = (CEconItemAttributeInitFromKV_fn) (FindPattern(base, base + size, "\x55\x8B\xEC\x53\x8B\x5D\x08\x56\x8B\xF1\x8B\xCB\x57\xE8\x2A\x2A\x2A\x2A", 18));
  109. #elif _LINUX
  110. Dl_info info;
  111. if (!dladdr(server, &info)) {
  112. return false;
  113. }
  114. // locate symbols within our server binary
  115. elf_version(EV_CURRENT);
  116. int fd = open(info.dli_fname, O_RDONLY);
  117. Elf *elf = elf_begin(fd, ELF_C_READ, NULL);
  118. Elf_Scn *scn = NULL;
  119. GElf_Shdr shdr;
  120. while ((scn = elf_nextscn(elf, scn)) != NULL) {
  121. gelf_getshdr(scn, &shdr);
  122. if (shdr.sh_type == SHT_SYMTAB) {
  123. break;
  124. }
  125. }
  126. Elf_Data *data = elf_getdata(scn, NULL);
  127. size_t count = shdr.sh_size / shdr.sh_entsize;
  128. /* print the symbol names */
  129. for (size_t i = 0; i < count; ++i) {
  130. GElf_Sym sym;
  131. gelf_getsym(data, i, &sym);
  132. const char *symname = elf_strptr(elf, shdr.sh_link, sym.st_name);
  133. if (!strcmp(symname,
  134. "_ZN28CEconItemAttributeDefinition11BInitFromKVEP9KeyValuesP10CUtlVectorI10CUtlString10CUtlMemoryIS3_iEE")) {
  135. fnItemAttributeInitFromKV = (CEconItemAttributeInitFromKV_fn) (reinterpret_cast<uintptr_t>(info.dli_fbase) + sym.st_value);
  136. } else if (!strcmp(symname, "_Z15GEconItemSchemav")) {
  137. fnGetEconItemSchema = reinterpret_cast<GetEconItemSchemaFn_t*>(reinterpret_cast<uintptr_t>(info.dli_fbase) + sym.st_value);
  138. }
  139. }
  140. elf_end(elf);
  141. close(fd);
  142. #endif
  143. if (!fnItemAttributeInitFromKV || !fnGetEconItemSchema) {
  144. META_CONPRINTF("Failed to get GEIS or BIFKV\n");
  145. return false;
  146. }
  147. // is this late enough in the MM:S load stage? we might just have to hold the function
  148. g_SchemaAttributes = reinterpret_cast<AttributeMap*>(fnGetEconItemSchema() + 0x1BC);
  149. return true;
  150. }
  151. bool DynSchema::Unload(char *error, size_t maxlen) {
  152. SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  153. return true;
  154. }
  155. bool AddAttribute(KeyValues *pAttribKV) {
  156. int attrdef = atoi(pAttribKV->GetName());
  157. // TODO add a copy of these tests in native
  158. if (attrdef <= 0) {
  159. return false;
  160. }
  161. if (g_SchemaAttributes->IsValidIndex(g_SchemaAttributes->Find(attrdef))) {
  162. return false;
  163. }
  164. CEconItemAttributeDefinition def;
  165. fnItemAttributeInitFromKV(&def, pAttribKV, nullptr);
  166. g_SchemaAttributes->Insert(attrdef, def);
  167. return true;
  168. }
  169. bool DynSchema::Hook_LevelInitPost(const char *pMapName, char const *pMapEntities,
  170. char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) {
  171. // this hook should fire shortly after the schema is (re)initialized
  172. // TODO determine if the schema was updated, we can do this by:
  173. // - adding a sentinel attribute that we test the existence of later, or
  174. // - check in LevelInitPre if we have a non-null CEconItemSchema::m_pDelayedSchemaData
  175. // TODO create a map of existing attribute names
  176. char game_path[256];
  177. engine->GetGameDir(game_path, sizeof(game_path));
  178. char buffer[1024];
  179. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s",
  180. game_path, "addons/dynattrs/items_dynamic.txt");
  181. KeyValues::AutoDelete pItemKV("DynamicSchema");
  182. if (pItemKV->LoadFromFile(basefilesystem, buffer)) {
  183. KeyValues *pKVAttributes = pItemKV->FindKey( "attributes" );
  184. if (pKVAttributes) {
  185. FOR_EACH_TRUE_SUBKEY(pKVAttributes, pKVAttribute) {
  186. AddAttribute(pKVAttribute);
  187. }
  188. }
  189. META_CONPRINTF("Successfully injected custom schema %s\n", buffer);
  190. } else {
  191. META_CONPRINTF("Failed to inject custom schema %s\n", buffer);
  192. }
  193. return true;
  194. }
  195. void DynSchema::AllPluginsLoaded() {
  196. /* This is where we'd do stuff that relies on the mod or other plugins
  197. * being initialized (for example, cvars added and events registered).
  198. */
  199. }
  200. bool DynSchema::Pause(char *error, size_t maxlen) {
  201. return true;
  202. }
  203. bool DynSchema::Unpause(char *error, size_t maxlen) {
  204. return true;
  205. }
  206. const char *DynSchema::GetLicense() {
  207. return "Proprietary";
  208. }
  209. const char *DynSchema::GetVersion() {
  210. return "1.0.1";
  211. }
  212. const char *DynSchema::GetDate() {
  213. return __DATE__;
  214. }
  215. const char *DynSchema::GetLogTag() {
  216. return "dynschema";
  217. }
  218. const char *DynSchema::GetAuthor() {
  219. return "nosoop";
  220. }
  221. const char *DynSchema::GetDescription() {
  222. return "Injects user-defined content into the game schema";
  223. }
  224. const char *DynSchema::GetName() {
  225. return "TF2 Dynamic Schema";
  226. }
  227. const char *DynSchema::GetURL() {
  228. return "https://git.csrd.science/";
  229. }