mmsplugin.cpp 7.3 KB

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