mmsplugin.cpp 12 KB

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