mmsplugin.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. void BindToSourceMod();
  16. bool SM_LoadExtension(char *error, size_t maxlength);
  17. void SM_UnloadExtension();
  18. SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
  19. SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, 0, bool, char const *, char const *, char const *, char const *, bool, bool);
  20. DynSchema g_Plugin;
  21. IServerGameDLL *server = nullptr;
  22. IVEngineServer *engine = NULL;
  23. IFileSystem *filesystem = nullptr;
  24. PLUGIN_EXPOSE(DynSchema, g_Plugin);
  25. class ISchemaAttributeType;
  26. // this may need to be updated in the future
  27. class CEconItemAttributeDefinition
  28. {
  29. public:
  30. // TODO implementing ~CEconItemAttributeDefinition segfaults. not sure what's up.
  31. // ideally we implement it to match the game so InsertOrReplace is sure to work correctly
  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. typedef uintptr_t (*GetEconItemSchema_fn)(void);
  61. GetEconItemSchema_fn 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. const char* NATIVE_ATTRIB_DIR = "addons/sourcemod/configs/tf2nativeattribs";
  70. bool DynSchema::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
  71. {
  72. PLUGIN_SAVEVARS();
  73. GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
  74. GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
  75. GET_V_IFACE_CURRENT(GetFileSystemFactory, filesystem, IFileSystem, FILESYSTEM_INTERFACE_VERSION);
  76. SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  77. // get the base address of the server
  78. #if _WINDOWS
  79. CWinLibInfo lib(server);
  80. lib.LocatePattern("\xE8\x2A\x2A\x2A\x2A\x83\xC0\x04\xC3", 9, (void**) &fnGetEconItemSchema);
  81. lib.LocatePattern("\x55\x8B\xEC\x53\x8B\x5D\x08\x56\x8B\xF1\x8B\xCB\x57\xE8\x2A\x2A\x2A\x2A", 18, (void**) &fnItemAttributeInitFromKV);
  82. #elif _LINUX
  83. CLinuxLibInfo lib(server);
  84. lib.LocateSymbol("_ZN28CEconItemAttributeDefinition11BInitFromKVEP9KeyValuesP10CUtlVectorI10CUtlString10CUtlMemoryIS3_iEE",
  85. (void**) &fnItemAttributeInitFromKV);
  86. lib.LocateSymbol("_Z15GEconItemSchemav", (void**) &fnGetEconItemSchema);
  87. #endif
  88. if (!fnItemAttributeInitFromKV || !fnGetEconItemSchema) {
  89. META_CONPRINTF("Failed to get GEIS or BIFKV\n");
  90. return false;
  91. }
  92. // is this late enough in the MM:S load stage? we might just have to hold the function
  93. g_SchemaAttributes = reinterpret_cast<AttributeMap*>(fnGetEconItemSchema() + 0x1BC);
  94. return true;
  95. }
  96. bool DynSchema::Unload(char *error, size_t maxlen) {
  97. SM_UnloadExtension();
  98. SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  99. return true;
  100. }
  101. /**
  102. * Initializes a CEconItemAttributeDefinition from a KeyValues definition, then inserts or
  103. * replaces the appropriate entry in the schema.
  104. */
  105. bool InsertOrReplaceAttribute(KeyValues *pAttribKV) {
  106. /**
  107. * TODO implement special handling when "auto" is provided; use an autoincrementing value
  108. * that checks for a free slot in the attribute mapping, then internally map the attribute
  109. * name to that value for persistence and so we don't add that attribute multiple times
  110. */
  111. int attrdef = atoi(pAttribKV->GetName());
  112. if (attrdef <= 0) {
  113. return false;
  114. }
  115. // only replace existing injected attributes; fail on schema attributes
  116. auto existingIndex = g_SchemaAttributes->Find(attrdef);
  117. if (existingIndex != g_SchemaAttributes->InvalidIndex()) {
  118. auto &existingAttr = g_SchemaAttributes->Element(existingIndex);
  119. if (!existingAttr.m_KeyValues->GetBool("injected")) {
  120. META_CONPRINTF("WARN: Not overriding native attribute '%s'\n",
  121. existingAttr.m_pszName);
  122. return false;
  123. }
  124. }
  125. // embed additional custom data into attribute KV; econdata and the like can deal with this
  126. // one could also add this data into the file itself, but this leaves less room for error
  127. pAttribKV->SetBool("injected", true);
  128. CEconItemAttributeDefinition def;
  129. fnItemAttributeInitFromKV(&def, pAttribKV, nullptr);
  130. // TODO verify that this doesn't leak, or just shrug it off
  131. g_SchemaAttributes->InsertOrReplace(attrdef, def);
  132. return true;
  133. }
  134. bool DynSchema::Hook_LevelInitPost(const char *pMapName, char const *pMapEntities,
  135. char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) {
  136. // this hook should fire shortly after the schema is (re)initialized
  137. char game_path[256];
  138. engine->GetGameDir(game_path, sizeof(game_path));
  139. char buffer[1024];
  140. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s",
  141. game_path, "addons/dynattrs/items_dynamic.txt");
  142. // always initialize attributes -- it's better than losing attributes on schema reinit
  143. // coughhiddendevattributescough
  144. // collect raw attribute keyvalue entries scattered across files
  145. KeyValues::AutoDelete rawAttributes("attributes");
  146. // read our own dynamic schema file -- this one supports other sections
  147. KeyValues::AutoDelete pKVMainConfig("DynamicSchema");
  148. if (pKVMainConfig->LoadFromFile(filesystem, buffer)) {
  149. KeyValues *pKVAttributes = pKVMainConfig->FindKey( "attributes" );
  150. if (pKVAttributes) {
  151. rawAttributes->RecursiveMergeKeyValues(pKVAttributes);
  152. META_CONPRINTF("Successfully injected custom schema %s\n", buffer);
  153. } else {
  154. META_CONPRINTF("Failed to inject custom schema %s\n", buffer);
  155. }
  156. }
  157. // iterate over TF2 Hidden Dev Attributes KV format
  158. // https://forums.alliedmods.net/showthread.php?t=326853
  159. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s/*", game_path, NATIVE_ATTRIB_DIR);
  160. FileFindHandle_t findHandle;
  161. const char *filename = filesystem->FindFirst(buffer, &findHandle);
  162. while (filename) {
  163. char pathbuf[1024];
  164. g_SMAPI->PathFormat(pathbuf, sizeof(pathbuf), "%s/%s/%s", game_path,
  165. NATIVE_ATTRIB_DIR, filename);
  166. if (!filesystem->FindIsDirectory(findHandle)) {
  167. KeyValues::AutoDelete nativeAttribConfig("attributes");
  168. nativeAttribConfig->LoadFromFile(filesystem, pathbuf);
  169. rawAttributes->RecursiveMergeKeyValues(nativeAttribConfig);
  170. META_CONPRINTF("Discovered custom schema %s\n", pathbuf);
  171. }
  172. filename = filesystem->FindNext(findHandle);
  173. }
  174. filesystem->FindClose(findHandle);
  175. // perhaps add some other validations before we actually process our attributes?
  176. // TODO ensure the name doesn't clash with existing / newly injected attributes
  177. // finally process our attributes
  178. FOR_EACH_TRUE_SUBKEY(rawAttributes, kv) {
  179. InsertOrReplaceAttribute(kv);
  180. }
  181. return true;
  182. }
  183. void DynSchema::AllPluginsLoaded() {
  184. /* This is where we'd do stuff that relies on the mod or other plugins
  185. * being initialized (for example, cvars added and events registered).
  186. */
  187. BindToSourceMod();
  188. }
  189. void* DynSchema::OnMetamodQuery(const char* iface, int *ret) {
  190. if (strcmp(iface, SOURCEMOD_NOTICE_EXTENSIONS) == 0) {
  191. BindToSourceMod();
  192. }
  193. if (ret != NULL) {
  194. *ret = IFACE_OK;
  195. }
  196. return NULL;
  197. }
  198. void BindToSourceMod() {
  199. char error[256];
  200. if (!SM_LoadExtension(error, sizeof(error))) {
  201. char message[512];
  202. snprintf(message, sizeof(message), "Could not load as a SourceMod extension: %s\n", error);
  203. engine->LogPrint(message);
  204. }
  205. }
  206. bool SM_LoadExtension(char *error, size_t maxlength) {
  207. if ((smexts = (IExtensionManager *)
  208. g_SMAPI->MetaFactory(SOURCEMOD_INTERFACE_EXTENSIONS, NULL, NULL)) == NULL) {
  209. if (error && maxlength) {
  210. snprintf(error, maxlength, SOURCEMOD_INTERFACE_EXTENSIONS " interface not found");
  211. }
  212. return false;
  213. }
  214. /* This could be more dynamic */
  215. char path[256];
  216. g_SMAPI->PathFormat(path, sizeof(path), "addons/dynattrs/tf2dynschema%s",
  217. #if defined __linux__
  218. "_mm.so"
  219. #else
  220. ".dll"
  221. #endif
  222. );
  223. if ((myself = smexts->LoadExternal(&g_Plugin, path, "dynschema.ext", error, maxlength))
  224. == NULL) {
  225. SM_UnsetInterfaces();
  226. return false;
  227. }
  228. return true;
  229. }
  230. void SM_UnloadExtension() {
  231. smexts->UnloadExtension(myself);
  232. }
  233. bool DynSchema::Pause(char *error, size_t maxlen) {
  234. return true;
  235. }
  236. bool DynSchema::Unpause(char *error, size_t maxlen) {
  237. return true;
  238. }
  239. const char *DynSchema::GetLicense() {
  240. return "GPLv3+";
  241. }
  242. const char *DynSchema::GetVersion() {
  243. return "1.2.1";
  244. }
  245. const char *DynSchema::GetDate() {
  246. return __DATE__;
  247. }
  248. const char *DynSchema::GetLogTag() {
  249. return "dynschema";
  250. }
  251. const char *DynSchema::GetAuthor() {
  252. return "nosoop";
  253. }
  254. const char *DynSchema::GetDescription() {
  255. return "Injects user-defined content into the game schema";
  256. }
  257. const char *DynSchema::GetName() {
  258. return "TF2 Dynamic Schema";
  259. }
  260. const char *DynSchema::GetURL() {
  261. return "https://git.csrd.science/";
  262. }
  263. bool DynSchema::OnExtensionLoad(IExtension *me, IShareSys *sys, char* error, size_t maxlength, bool late) {
  264. sharesys = sys;
  265. myself = me;
  266. /* Get the default interfaces from our configured SDK header */
  267. if (!SM_AcquireInterfaces(error, maxlength)) {
  268. return false;
  269. }
  270. return true;
  271. }
  272. void DynSchema::OnExtensionUnload() {
  273. SM_UnsetInterfaces();
  274. }
  275. void DynSchema::OnExtensionsAllLoaded() {
  276. // no-op
  277. }
  278. void DynSchema::OnExtensionPauseChange(bool pause) {
  279. // no-op
  280. }
  281. bool DynSchema::QueryRunning(char *error, size_t maxlength) {
  282. return true;
  283. }
  284. bool DynSchema::IsMetamodExtension() {
  285. return true;
  286. }
  287. const char *DynSchema::GetExtensionName() {
  288. return this->GetName();
  289. }
  290. const char *DynSchema::GetExtensionURL() {
  291. return this->GetURL();
  292. }
  293. const char *DynSchema::GetExtensionTag() {
  294. return this->GetLogTag();
  295. }
  296. const char *DynSchema::GetExtensionAuthor() {
  297. return this->GetAuthor();
  298. }
  299. const char *DynSchema::GetExtensionVerString() {
  300. return this->GetVersion();
  301. }
  302. const char *DynSchema::GetExtensionDescription() {
  303. return this->GetDescription();
  304. }
  305. const char *DynSchema::GetExtensionDateString() {
  306. return this->GetDate();
  307. }